Android and Java EE communication: Login Interface Super Lite

Source: Internet
Author: User

Today, the use of Android and Tomcat server to complete the simple interface of communication.

The main is the user input ID and password, the interface shows the login success or failure.

Yesterday after the completion of the code, not yet time to debug, today through debugging, found the following errors:

1. Forget to start the Tomcat server when testing (OK this is a stupid mistake.) )

2. The "UTF-8" in the encoding format of the client settings is written as "Utf_8" (well I know it's stupid ...). )

3. When transmitting data, the data returned by the server is inconsistent with the format of the client receiving data, resulting in garbled characters.

4. Attempting to change the client display interface in a newly opened thread that is used to access the network causes an error.

Through debugging, successfully solved these problems, and finally implemented a simplified login. The implementation steps are roughly as follows:

1 "Create a user table in the database (I only set the Id,password parameter)

2 "New Java class user in Java EE

3> in user to get the user information to be called in the servlet (part of the code)

public int finduser (int id,string password) throws ClassNotFoundException, sqlexception{
Establish a link to the database to find out if the user exists

Class.forName ("Com.mysql.jdbc.Driver");

fill in the information here
String dbName = "";
String tableName = "R";
String user = "";
String Mysql_password = "I";

String url = "jdbc:mysql://localhost:3306/" + DbName + "? user="
+user + "&password=" + Mysql_password;

Connection conn = (Connection) drivermanager.getconnection (URL);

Get database data, perform query operations
Statement Statement = (Statement) conn.createstatement ();

String sql = "SELECT * from" + tableName;

ResultSet rs = (ResultSet) statement.executequery (SQL);

Presence State volume flag, 1 for presence, 0 for non-existent
int exist = 0;

while (Rs.next ()) {
int user_name = Rs.getint (1);
String User_password = rs.getstring (2);
if (user_name = = ID && user_password.equals (password)) {
exist = 1;
Break
}

}
return exist;
}

4 new Servlet file, write response and reply code (part of the code):

protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {
TODO auto-generated Method Stub
Request.setcharacterencoding ("UTF-8");
Response.setcontenttype ("Text/json;charset=utf-8");
String Reqmessage,respmessage;
BufferedReader br = new BufferedReader (New InputStreamReader (Request.getinputstream (), "UTF-8"));
StringBuffer sb = new StringBuffer ("");
String temp;
while (temp = br.readline ()) = null) {
Sb.append (temp);
}
Br.close ();

Reqmessage = Sb.tostring ();
Jsonarray Jsonarray = Jsonarray.fromobject (reqmessage);
Jsonobject data = (jsonobject) jsonarray.get (0);
int user_id = Data.getint ("id");
String User_password = data.getstring ("password");
User U = new user ();
int exist = 0;
try {
exist = U.finduser (user_id, User_password);
} catch (ClassNotFoundException e) {
TODO auto-generated Catch block
E.printstacktrace ();
} catch (SQLException e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
PrintWriter pw = Response.getwriter ();
Pw.write (exist+ "");
Pw.flush ();
Pw.close ();

}

At this point, the service side of the code is basically completed, and then the client's code.

The core code for the client is as follows (some code):

Httpparams httpparams = new Basichttpparams ();
HttpClient HC = new Defaulthttpclient (httpparams);
String addr = "Http://172.16.121.16:8080/xiangyue/loginServlet";
HttpPost hp = new HttpPost (addr);
SYSTEM.OUT.PRINTLN ("Connection Successful! ");
System.out.println (Reqvalue);
try {
Hp.setentity (New Stringentity (Reqvalue.tostring (), "UTF-8"));
HttpResponse hr = Hc.execute (HP);

if (Hr.getstatusline (). Getstatuscode () = = 200) {
returnvalue = entityutils.tostring (Hr.getentity (), "UTF-8");
System.out.println (returnvalue);
if (Returnvalue.equals ("1")) {
SYSTEM.OUT.PRINTLN ("Login Successful! ");
Toast.maketext (Mainactivity.this, "Login successful! ", Toast.length_long). Show ();
exist = 1;
}
else{
SYSTEM.OUT.PRINTLN ("This user does not exist! ");
Toast.maketext (Mainactivity.this, "username or password is wrong! ", Toast.length_long). Show ();
exist = 0;
}
}else{
SYSTEM.OUT.PRINTLN ("Response failed! ");
}
} catch (Unsupportedencodingexception e) {
TODO Auto-generated catch block
E.printstacktrace ();
} catch (Clientprotocolexception e) {
TODO Auto-generated catch block
E.printstacktrace ();
} catch (IOException e) {
TODO Auto-generated catch block
E.printstacktrace ();
}

At this point the core code is completed, a little add interface or something can be tested (required package to all successful import, environment configuration is complete). If there is any need to modify the optimization of the place, hope the great God advice ~

Android and Java EE communication: Login Interface Super Lite

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.