现在的位置: 首页 > 综合 > 正文

Android Tomcat 的应用之服务器部分

2013年02月04日 ⁄ 综合 ⁄ 共 2048字 ⁄ 字号 评论关闭

        接着昨天的写,实现登录的服务端部分。首先得弄个数据库,然后建立一个表,存储所有用户的用户名和密码,当在客户端发出查询请求的时候会把用户输入的用户名和密码传到服务器端,然后在数据库中进行查询,这里我们的表就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;
	}

}

         最后就是实现servlet,主要是处理来自客户端的查询请求和返回查询结果:

public class Login extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		UserDao dao = new UserDaoImpl();
		// 获得客户端请求参数
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		User u = dao.login(username, password);
		if(u!=null){
			out.print("登录成功");
		}else{
			out.print("null");
		}
		out.flush();
		out.close();
	}
	

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}
	public void init() throws ServletException {
	}
	
	public LoginServlet() {
		super();
	}

	public void destroy() {
		super.destroy();
	}

}

           至于Tomcat和MySQL的配置、使用网上有不少教程!至此就可以实现登录模块了!

抱歉!评论已关闭.