歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android Tomcat 的應用之服務器部分

Android Tomcat 的應用之服務器部分

日期:2017/3/1 10:27:24   编辑:Linux編程

接著這裡(http://www.linuxidc.com/Linux/2012-03/55917.htm)寫,實現登錄的服務端部分。首先得弄個數據庫,然後建立一個表,存儲所有用戶的用戶名和密碼,當在客戶端發出查詢請求的時候會把用戶輸入的用戶名和密碼傳到服務器端,然後在數據庫中進行查詢,這裡我們的表就3個字段,一個ID,一個username和一個password。

然後就是編碼實現了,首先是寫一個類封裝一下數據庫中的用戶信息,如下:

  1. public class User {
  2. private int id;
  3. private String username;
  4. private String password;
  5. public int getId() {
  6. return id;
  7. }
  8. public void setId(int id) {
  9. this.id = id;
  10. }
  11. public String getName() {
  12. return username;
  13. }
  14. public void setName(String name) {
  15. this.name = name;
  16. }
  17. public String getPassword() {
  18. return password;
  19. }
  20. public void setPassword(String password) {
  21. this.password = password;
  22. }
  23. }

然後就是定義查詢的接口:

  1. public interface UserDao {
  2. // 登錄方法
  3. public User login(String username,String password);
  4. }

實現該接口:

  1. public class UserDaoImpl implements UserDao {
  2. public User login(String account, String password) {
  3. // 查詢SQL語句
  4. String querySql = " select id,username,password "+
  5. " from userTable "+
  6. " where username=? and password=? ";
  7. DBUtil util = new DBUtil();
  8. Connection conn = util.openConnection();
  9. try {
  10. PreparedStatement state = conn.prepareStatement(querySql);
  11. state.setString(1, username);
  12. state.setString(2, password);
  13. ResultSet result = state.executeQuery();
  14. if (result.next()) {
  15. int id = result.getInt(1);
  16. String name = result.getString(4);
  17. User user = new User();
  18. user.setId(id);
  19. user.setName(username);
  20. user.setPassword(password);
  21. return user;
  22. }
  23. } catch (SQLException e) {
  24. e.printStackTrace();
  25. } finally {
  26. util.closeConn(conn);
  27. }
  28. return null;
  29. }
  30. }
Copyright © Linux教程網 All Rights Reserved