Wireless ordering for Android projects (2)--Client and server-side implementations of user logins

Source: Internet
Author: User

First, server-side implementation

(1) Creating a dynamic server project


Part of the code is as follows:

Package Com.lc.dao;import Java.sql.connection;import Java.sql.drivermanager;import java.sql.sqlexception;public Class Connectionutil {/** * Open connection *  * @return */public static Connection open () {//1.url//2.driver//3.username//4.P assword//configuration file XML properties file propertiesstring Driver = "Com.mysql.jdbc.Driver"; String url = "JDBC:MYSQL://LOCALHOST:3306/WIRESSORDER?USEUNICODE=TRUE&CHARACTERENCODING=GBK"; String username = "Xuuu"; String password = "1234567890"; try {class.forname (driver); return drivermanager.getconnection (URL, username, password) ;} catch (ClassNotFoundException e) {e.printstacktrace ();} catch (SQLException e) {e.printstacktrace ();} return null;} /** * Close Connection *  * @param conn */public static void Close (Connection conn) {if (conn! = null) {try {conn.close ();} catch ( SQLException e) {e.printstacktrace ();}}}}

Package com.lc.dao;/* * The user table in the corresponding database *  * Entity class or JavaBean---usertabl ORM */public class User {private String us ername;private String password;private Int id;/* * Non-parametric construction method */public User () {super ();} /* * Parameter construction method */public User (string Username, string password, int id) {super (); this.username = Username;this.password = pas sword;this.id = ID;} Public String GetUserName () {return username;} public void Setusername (String username) {this.username = username;} Public String GetPassword () {return password;} public void SetPassword (String password) {this.password = password;} public int getId () {return ID;} public void setId (int id) {this.id = id;}}

package  com.lc.dao;/* * Userdao Interface * * defined in user-related method */public interface Userdao {//Implement user login Public user login (string username, string password);} 
package Com.lc.dao;import Java.sql.connection;import Java.sql.preparedstatement;import Java.sql.ResultSet;import java.sql.sqlexception;/* * For implementing methods defined in Userdao * * Interface Implementation Class */public class Userdaoimpl implements Userdao {@Overridepublic Us ER login (string username, string password) {Connection Connection = Connectionutil.open (); String sql = "Select Id,username,password from Usertbl where username=?" and password=? "; try {//Pre-search PreparedStatement pstmt = connection.preparestatement (sql);p stmt.setstring (1, username);p stmt.setstring (2 , password); ResultSet rs = Pstmt.executequery (); if (Rs.next ()) {int id = rs.getint (1);//Get a user's iduser user = new User ();//Set data user. SetId (ID); User.setusername (username); User.setpassword (password); return user;}} catch (SQLException e) {e.printstacktrace ();} Finally{connectionutil.close (connection);} return null;}} 
Package Com.lc.servlet;import Java.io.ioexception;import Java.io.printwriter;import javax.servlet.ServletException ; Import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Com.lc.dao.user;import Com.lc.dao.userdao;import Com.lc.dao.userdaoimpl;public class Loginservlet extends HttpServlet {private static final long Serialversionuid = 1l;pub Lic Loginservlet () {super ();} protected void doget (HttpServletRequest request,httpservletresponse response) throws Servletexception, IOException { DoPost (request, response); are executed dopost}protected void DoPost (httpservletrequest request,httpservletresponse response) throws Servletexception, IOException {response.setcontenttype ("Text/html;charset=utf8");//Set encoding printwriter out = Response.getwriter ();// Get login Request Information String username = Request.getparameter ("username"); String Password = request.getparameter ("password");//Print out test: http://localhost:8080/WiressOrderServer/LoginServlet?username=tom&password=123//System.out.println ("Username:" + username + "Password:" + password); Userdao Userdao = new Userdaoimpl (); User user = Userdao.login (username, password), if (user! = null) {SYSTEM.OUT.PRINTLN ("username:" + user.getusername () + "PA ssWOrd: "+ User.getpassword ()); Out.println (" Username: "+ user.getusername () +" Password: "+ User.getpassword ());} else {System.out.println ("without the user you want, login failed! "); Out.println (" Login failed without the user you want! ") ");} Out.flush (); Out.close ();}}

Second, the client implementation


Layout file:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:orientation=" vertical " > <linearlayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android oid:orientation= "Horizontal" > <textview android:id= "@+id/tv_username" Android:layout_w         Idth= "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/login_password"/> <edittext android:id= "@+id/ed_username" android:layout_width= "Wrap_content" an droid:layout_height= "Wrap_content" android:ems= "android:inputtype=" Textpersonname "/> < /linearlayout> <linearlayout android:layout_width= "fill_parent" android:layout_height= "wrap_content "Android:orientation=" HorizOntal "> <textview android:id=" @+id/tv_password "android:layout_width=" Wrap_content "            android:layout_height= "Wrap_content" android:text= "@string/login_username"/> <edittext Android:id= "@+id/ed_password" android:layout_width= "Wrap_content" android:layout_height= "W Rap_content "android:ems=" android:inputtype= "Textpassword" > <requestfocus/&gt        ; </EditText> </LinearLayout> <button android:id= "@+id/login_button" android:layout_width = "Wrap_content" android:layout_height= "wrap_content" android:text= "@string/login_loginbutton"/></Line Arlayout>



Package Com.xuliugen.wiressorderclient;import Java.io.ioexception;import java.io.UnsupportedEncodingException; Import Java.util.list;import Org.apache.http.httpentity;import Org.apache.http.httpresponse;import Org.apache.http.namevaluepair;import Org.apache.http.client.httpclient;import Org.apache.http.client.entity.urlencodedformentity;import Org.apache.http.client.methods.httppost;import Org.apache.http.impl.client.defaulthttpclient;import Org.apache.http.util.entityutils;public class HttpUtil { public static string DoPost (string url, list<namevaluepair> List) {HttpPost post = new HttpPost (URL); httpentity entity = null;if (list! = null) {try {entity = new urlencodedformentity (list, "GBK");} catch (Unsupportedencodi Ngexception e) {e.printstacktrace ();} Post.setentity (entity);} HttpClient client = new defaulthttpclient (); try {httpresponse response = Client.execute (post); if ( Response.getstatusline (). Getstatuscode () = = () {String result = entityutils.tostring (response.getentity ());// Save Sharedpre...result = new String (result.getbytes ("iso-8859-1"), "GBK"); SYSTEM.OUT.PRINTLN (result); return result;}} catch (IOException e) {e.printstacktrace ();} return null;}}

Package Com.xuliugen.wiressorderclient;import Java.util.arraylist;import Java.util.list;import Org.apache.http.namevaluepair;import Org.apache.http.message.basicnamevaluepair;import android.app.Activity; Import Android.os.asynctask;import Android.os.bundle;import Android.view.view;import Android.view.view.onclicklistener;import Android.widget.button;import Android.widget.edittext;import Android.widget.toast;public class Loginactivity extends Activity {private EditText usernameedittext, Passwordedittext; Private Button Login_button; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.login); usernameedittext = (EditText) This.findviewbyid (R.id.ed_ username);p Asswordedittext = (EditText) This.findviewbyid (r.id.ed_password); Login_button = (Button) This.findviewbyid (R.id.login_button); Login_button.setonclicklistener (new Onclicklistener () {@Overridepublic void OnClick (View v) {String url = "Http://172.23.252.89:8080/WiressOrderSErver/loginservlet ";//execute Asynchronous Task New MyTask (). Execute (URL);});} String dologin (string url) {String username = Usernameedittext.gettext (). toString (); String password = Passwordedittext.gettext (). toString ();//1.apache clientlist<namevaluepair> list = new Arraylist<namevaluepair> (); Namevaluepair P1 = new Basicnamevaluepair ("username", username); Namevaluepair P2 = new Basicnamevaluepair ("password", password); List.add (p1); List.add (p2); String msg = httputil.dopost (URL, list); return msg;} Multithreading usage: hander, Asynctaskclass MyTask extends Asynctask<string, Integer, string> {@Overrideprotected String Doinbackground (String ... params) {string url = params[0]; String result = Dologin (URL); return result;} @Overrideprotected void OnPostExecute (String result) {Super.onpostexecute (result);//1. Save Information Toast.maketext ( Getapplicationcontext (), result, Toast.length_short). Show ();}}




Wireless ordering for Android projects (2)--Client and server-side implementations of user logins

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.