Android Tomcat 的应用之服务器部分
接着昨天http://www.zzzyk.com/kf/201203/124792.html 的写,实现登录的服务端部分。首先得弄个数据库,然后建立一个表,存储所有用户的用户名和密码,当在客户端发出查询请求的时候会把用户输入的用户名和密码传到服务器端,然后在数据库中进行查询,这里我们的表就3个字段,一个ID,一个username和一个password。
然后就是编码实现了,首先是写一个类封装一下数据库中的用户信息,如下:
[java] 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 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;
}
} 然后就是定义查询的接口:
[java] public inte易做图ce UserDao {
// 登录方法
public User login(String username,String password);
}
public inte易做图ce UserDao {
// 登录方法
public User login(String username,String password);
} 实现该接口:
[java] 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;
}
}
public class UserDaoImpl implements UserDao {
public User login(String account, String password) {
// 查询SQL语句www.zzzyk.com
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;
}
} 最后就是实现servlet,主要是处理来自客户端的查询请求和返回查询结果:
[java] public class Login extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletRespons
补充:移动开发 , Android ,