Android項目之無線點餐(2)--使用者登入的用戶端和伺服器端實現

來源:互聯網
上載者:User

標籤:android項目之無線點餐2--使用者登

一、伺服器端實現

(1)建立動態伺服器項目


個部分代碼如下:

package com.lc.dao;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;public class ConnectionUtil {/** * 開啟串連 *  * @return */public static Connection open() {// 1.url// 2.driver// 3.username// 4.password// 設定檔xml 屬性檔案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;}/** * 關閉串連 *  * @param conn */public static void close(Connection conn) {if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}}}

package com.lc.dao;/* * 對應資料庫中的user表 *  * Entity Class或者是JavaBean---UserTabl ORM */public class User {private String username;private String password;private int id;/* * 無參的構造方法 */public User() {super();}/* * 有參的構造方法 */public User(String username, String password, int id) {super();this.username = username;this.password = password;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介面 *  * 定義於User有關的方法 */public interface UserDao {// 實現使用者登入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;/* * 用於實現UserDao中定義的方法 *  * 介面的實作類別 */public class UserDaoImpl implements UserDao {@Overridepublic User login(String username, String password) {Connection connection = ConnectionUtil.open();String sql = "select id,username,password from UserTbl where username=? and password=?";try {// 預查尋PreparedStatement pstmt = connection.prepareStatement(sql);pstmt.setString(1, username);pstmt.setString(2, password);ResultSet rs = pstmt.executeQuery();if (rs.next()) {int id = rs.getInt(1); // 獲得一個使用者的idUser user = new User();// 設定資料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;public LoginServlet() {super();}protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {doPost(request, response); // 都執行dopost}protected void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html;charset=utf8"); // 設定編碼方式PrintWriter out = response.getWriter();// 獲得登入的請求資訊String username = request.getParameter("username");String password = request.getParameter("password");// 列印出來測試: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() + "password:"+ user.getPassword());out.println("username:" + user.getUsername() + "password:"+ user.getPassword());} else {System.out.println("沒有你所要的使用者,登入失敗!");out.println("沒有你所要的使用者,登入失敗!");}out.flush();out.close();}}

二、用戶端實現


布局檔案:

<?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:orientation="horizontal" >        <TextView            android:id="@+id/tv_username"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/login_password" />        <EditText            android:id="@+id/ed_username"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:ems="10"            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="wrap_content"            android:ems="10"            android:inputType="textPassword" >            <requestFocus />        </EditText>    </LinearLayout>    <Button        android:id="@+id/login_button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/login_loginbutton" /></LinearLayout>



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 (UnsupportedEncodingException e) {e.printStackTrace();}post.setEntity(entity);}HttpClient client = new DefaultHttpClient();try {HttpResponse response = client.execute(post);if (response.getStatusLine().getStatusCode() == 200) {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);passwordEditText = (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";// 執行非同步任務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;}// 多線程的使用: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.儲存資訊Toast.makeText(getApplicationContext(), result, Toast.LENGTH_SHORT).show();}}}




Android項目之無線點餐(2)--使用者登入的用戶端和伺服器端實現

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.