登录端代码
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置查询码表
request.setCharacterEncoding("UTF-8");
//1、获得用户名和密码
String username = request.getParameter("username");
String password = request.getParameter("password");
//2、调用一个业务方法进行该用户查询
User login = null;
try {
login = login(username,password);
} catch (SQLException e) {
e.printStackTrace();
}
//3、通过user是否为null判断用户名和密码是否正确
if(login!=null){
//用户名和密码正确
//登录成功 跳转到网站的首页
response.sendRedirect(request.getContextPath());
}else{
//用户名或密码错误
//跳回当前login.jsp
//使用转发 转发到login.jsp 向request域中存储错误信息
request.setAttribute("loginInfo", "用户名或密码错误");
request.getRequestDispatcher("/login.jsp").forward(request, response);
}
}
public User login(String username,String password) throws SQLException{
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "select * from user where username=? and password=?";
User user = runner.query(sql, new BeanHandler(User.class), username,password);
return user;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
注册端
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置查询码表
request.setCharacterEncoding("UTF-8");
Mapproperties = request.getParameterMap();
User user = new User();
try {
BeanUtils.populate(user, properties);
} catch (IllegalAccessException | InvocationTargetException e) {
e.printStackTrace();
}
//现在这个位置 user对象已经封装好了
//手动封装uid----uuid---随机不重复的字符串32位--java代码生成后是36位
user.setUid(UUID.randomUUID().toString());
//3、将参数传递给一个业务操作方法
try {
regist(user);
} catch (SQLException e) {
e.printStackTrace();
}
//4、认为注册成功跳转到登录页面
response.sendRedirect(request.getContextPath()+"/login.jsp");
}
//注册的方法
public void regist(User user) throws SQLException {
//操作数据库
QueryRunner runner = new QueryRunner(DataSourceUtils.getDataSource());
String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
runner.update(sql,user.getUid(),user.getUsername(),user.getPassword(),user.getName(),
user.getEmail(),null,user.getBirthday(),user.getSex(),null,null);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
源码地址:
https://github.com/FoxconnPeter/-JavaWeb-