Java 如何在android中从servlet读取对象

Java 如何在android中从servlet读取对象,java,android,servlets,Java,Android,Servlets,我正在开发一个android应用程序,它必须与servlet对话才能访问数据库。我想将对象从servlet传递到我的android应用程序 这是我发送对象的servlet代码 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub

我正在开发一个android应用程序,它必须与servlet对话才能访问数据库。我想将对象从servlet传递到我的android应用程序

这是我发送对象的servlet代码

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    // TODO Auto-generated method stub      
    response.setContentType("text");

    String id = request.getParameter("id");
    try {
        Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
        java.sql.Connection con= DriverManager.getConnection("jdbc:odbc:Database");
        Statement statement = con.createStatement();

        PrintWriter p = response.getWriter();

        ResultSet rs = statement.executeQuery("select * from employee where PS="+id);

        while(rs.next()){
            Employee e = new Employee();
            e.setId(rs.getString("ID"));
            e.setPs(String.valueOf(rs.getDouble("PS")));
            e.setName(rs.getString("Emp_name"));
            e.setDept(rs.getString("Dept"));

            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
            objectOutputStream.writeObject(e);

        }

    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
我应该如何读取android应用程序中的对象。
谢谢。

你可以做各种事情来解决这个问题

a) 使用DAO实践阅读它来理解它基本上它将代码的实现划分为不同的段和类以便于您的理解。 但是,如果你不想经历所有这些麻烦,你可以做一些类似的事情。 a、 )创建一个单独的java类,在该类中编写处理Db的所有方法,如insert、select等。。 e、 g如果您在用户中登录。。方法是这样的

public int AuthenticateUser(String un, String pw, String phn) {
        System.out.println("I m in this method");
        Connection conn = (Connection) DBConnection.getInstance().getConnection();
        Statement pstmt = null;
        ResultSet rs = null;

        if (conn == null) {
            System.out.println("Connection error");
            check = -1;

        }


        try {
            String authenticatequery = "SELECT * FROM users WHERE uname = '"+un+"' && password =  '"+pw+"' && phoneno = '"+phn+"'";


            System.out.println(authenticatequery);
            pstmt = conn.createStatement();
            rs = pstmt.executeQuery(authenticatequery);
            System.out.println("I m in above try catch");

            // pstmt = conn.prepareStatement(authenticatequery);

            // rs = pstmt.executeQuery(authenticatequery);


            if (rs.next()) {
                System.out.println("I am in rs method");
                UserInfo  info = new UserInfo();
                rs.getString(1);
                rs.getString(2);
                rs.getString(3);
                //info.setUsername(rs.getString(un));
                System.out.println("i have the username" + un);
                //info.setPassword(rs.getString(un));
                System.out.println("I have got the password " + pw);

                System.out.println("I have got the password " + phn);

                System.out.println("User Exist");
                check = 1;
            } else {

                System.out.println("No user found");
                check = 0;
            }

            // rs.close();
            // pstmt.close();
            // conn.close();
        } catch (SQLException e) {
            // TODO: handle exception
            System.out.println("Exception-internal error");
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                    pstmt.close();
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

}
    return check;



}
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        //String username = request.getParameter("username");
    //  String password = request.getParameter("password");
        //UserInfo uinfo = new UserInfo();

    // uinfo.setUsername(username);
    // uinfo.setPassword(password);



        System.out.println("I am in process");

        PrintWriter out = response.getWriter();
          String un, pw,phn;

          un = request.getParameter("Usrnm");
          System.out.println(un);
          pw = request.getParameter("pwd");
          System.out.println(pw);

          phn = request.getParameter("phn");
          System.out.println(phn);

            Authenticate auth = new Authenticate();
            int check = auth.AuthenticateUser(un, pw,phn);
            System.out.println("My result is" + check);
          if (check==1){

              out.print(1);
          }  else{
               out.print(0);
              }
              }
    }
请注意int变量“check”,如果方法正确运行,它将返回“1”,否则返回“0”。。现在你可以使用这个检查作为你的优势,并通过servlet将其发送到你的android应用程序,如下所示

public int AuthenticateUser(String un, String pw, String phn) {
        System.out.println("I m in this method");
        Connection conn = (Connection) DBConnection.getInstance().getConnection();
        Statement pstmt = null;
        ResultSet rs = null;

        if (conn == null) {
            System.out.println("Connection error");
            check = -1;

        }


        try {
            String authenticatequery = "SELECT * FROM users WHERE uname = '"+un+"' && password =  '"+pw+"' && phoneno = '"+phn+"'";


            System.out.println(authenticatequery);
            pstmt = conn.createStatement();
            rs = pstmt.executeQuery(authenticatequery);
            System.out.println("I m in above try catch");

            // pstmt = conn.prepareStatement(authenticatequery);

            // rs = pstmt.executeQuery(authenticatequery);


            if (rs.next()) {
                System.out.println("I am in rs method");
                UserInfo  info = new UserInfo();
                rs.getString(1);
                rs.getString(2);
                rs.getString(3);
                //info.setUsername(rs.getString(un));
                System.out.println("i have the username" + un);
                //info.setPassword(rs.getString(un));
                System.out.println("I have got the password " + pw);

                System.out.println("I have got the password " + phn);

                System.out.println("User Exist");
                check = 1;
            } else {

                System.out.println("No user found");
                check = 0;
            }

            // rs.close();
            // pstmt.close();
            // conn.close();
        } catch (SQLException e) {
            // TODO: handle exception
            System.out.println("Exception-internal error");
        } finally {

            if (conn != null) {
                try {
                    conn.close();
                    pstmt.close();
                    conn.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

}
    return check;



}
protected void process(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        //String username = request.getParameter("username");
    //  String password = request.getParameter("password");
        //UserInfo uinfo = new UserInfo();

    // uinfo.setUsername(username);
    // uinfo.setPassword(password);



        System.out.println("I am in process");

        PrintWriter out = response.getWriter();
          String un, pw,phn;

          un = request.getParameter("Usrnm");
          System.out.println(un);
          pw = request.getParameter("pwd");
          System.out.println(pw);

          phn = request.getParameter("phn");
          System.out.println(phn);

            Authenticate auth = new Authenticate();
            int check = auth.AuthenticateUser(un, pw,phn);
            System.out.println("My result is" + check);
          if (check==1){

              out.print(1);
          }  else{
               out.print(0);
              }
              }
    }
在android应用程序中,您可以使用下面的代码调用响应对象,为通信添加自定义http客户端类

response = CustomHttpClient.executeHttpPost("http://192.1..11../HelloWorldServlet/LoginDriverServlet", postParameters);
现在,您可以使用响应对象并根据需要对其进行建模

if (res.equals("1")) {

                        Log.e("CHeck4 response","i m here");
                        Log.e("CHeck response", res);
                        //error.setText("Correct Username or Password");
                        Intent intent = new Intent(getApplicationContext(), SetStatus.class);

                        startActivity(intent);
                        setContentView(R.layout.activity_set_status);
                        Toast.makeText(getApplicationContext(), "Loggin In", Toast.LENGTH_LONG).show();
                    } else if(res.equals("0")) {
                        //error.setText("Sorry!! Incorrect Username or Password");
                        Log.e("CHeck3 response", "i m here");
                        Toast.makeText(getApplicationContext(), "Sorry!! Incorrect Username or Password", Toast.LENGTH_LONG).show();
                        Intent intent = new Intent();


                        //Username or Password",Toast.LENGTH_LONG).show();
                    }



Hope you get it..otherwise coments are welcomed :)

1) 内容类型应该比
文本
更合适。2) 看起来您希望在while循环中写入多个对象。3) 永远不要将SQL命令与来自HTTP客户机的值连接起来,请使用准备好的语句。4) 您必须使用
response.getWriter().write(…)
方法将
ObjectOutputStream
字节缓冲区实际写入客户端。5) 在客户端上,您可以使用
ObjectInputStream
@UdoKlimaschewski:您发自内心地说话。。。另外,对于web通信,为什么不使用标准化的东西,比如JSON、XML,甚至Google协议缓冲区呢?@ppeterka:这也是我的选择,编写序列化对象看起来有点吓人,但应该可以。只要双方都说同一个爪哇语。@UdoKlimaschewski“只要双方都说同一个爪哇语”:这是我非常非常害怕的事情……:)