新建UserException类
package com.xue.exception;
public class UserException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
public UserException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
}
在UserServiceImpl中,添加一个登录方法
@Override
public User login(User user) throws UserException {
// TODO Auto-generated method stub
User u=userDao.findUser(user.getUsername(), user.getPassword());
if(u!=null){
return u;
}else {
throw new UserException("用户名密码错误");
}
}
重构LoginServlet方法
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html;charset=utf-8");
User formUser = new User();
IUserService userService = new UserServiceImpl();
try {
BeanUtils.populate(formUser, request.getParameterMap());
User dbuser;
try {
dbuser=userService.login(formUser);
request.getSession().setAttribute("loginUsername", dbuser.getUsername());
response.getWriter().write("登陆成功,3秒后进入主页");
response.setHeader("refresh", "3;url=" + request.getContextPath() + "/main.jsp");
} catch (UserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response.getWriter().write("登陆失败,用户名或密码错误,3秒转回登陆页面");
response.setHeader("refresh", "3;url=" + request.getContextPath() + "/login.jsp");
}