接著這裡(http://www.linuxidc.com/Linux/2012-03/55917.htm)寫,實現登錄的服務端部分。首先得弄個數據庫,然後建立一個表,存儲所有用戶的用戶名和密碼,當在客戶端發出查詢請求的時候會把用戶輸入的用戶名和密碼傳到服務器端,然後在數據庫中進行查詢,這裡我們的表就3個字段,一個ID,一個username和一個password。
然後就是編碼實現了,首先是寫一個類封裝一下數據庫中的用戶信息,如下:
- public class User {
- private int id;
-
- private String username;
-
- private String password;
-
- public int getId() {
- return id;
- }
- public void setId(int id) {
- this.id = id;
- }
- public String getName() {
- return username;
- }
- public void setName(String name) {
- this.name = name;
- }
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
-
- }
然後就是定義查詢的接口:
- public interface UserDao {
- // 登錄方法
- public User login(String username,String password);
- }
實現該接口:
- public class UserDaoImpl implements UserDao {
- public User login(String account, String password) {
- // 查詢SQL語句
- String querySql = " select id,username,password "+
- " from userTable "+
- " where username=? and password=? ";
- DBUtil util = new DBUtil();
- Connection conn = util.openConnection();
- try {
- PreparedStatement state = conn.prepareStatement(querySql);
- state.setString(1, username);
- state.setString(2, password);
-
- ResultSet result = state.executeQuery();
- if (result.next()) {
-
- int id = result.getInt(1);
- String name = result.getString(4);
-
- User user = new User();
-
- user.setId(id);
- user.setName(username);
- user.setPassword(password);
-
- return user;
- }
- } catch (SQLException e) {
- e.printStackTrace();
- } finally {
- util.closeConn(conn);
- }
- return null;
- }
-
- }