packagecn.edu.aynu.rjxy.servlet;importjava.io.IOException;importjava.io.PrintWriter;importjavax.servlet.ServletException;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importcn.edu.aynu.rjxy.bean.User;importcn.edu.aynu.rjxy.exception.UserException;importcn.edu.aynu.rjxy.service.UserService;importcn.edu.aynu.rjxy.utils.CommonsUtils;/*** 调用UserService里面的方法
*@authorAdministrator
**/
public class UserServlet extendsHttpServlet {private UserService userService = newUserService();public voiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {this.doPost(request, response);
}public voiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {//处理中文乱码
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");//获取隐藏字段method的值,并把它转换为int型
int method = Integer.parseInt(request.getParameter("method"));switch(method) {case 1: this.register(request, response);break;case 2: this.login(request, response);break;
}
}public voidregister(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {/*** 1、将注册表单中的用户信息封装到user对象中
* 2、将获取的UUID值作为user对象的id
* 3、注册,如果发生异常,就到register.jsp页面上显示:用户已存在
* 如果成功,显示注册成功,3秒后就跳转到index.jsp页面。*/User user= CommonsUtils.toBean(request.getParameterMap(), User.class);
user.setId(CommonsUtils.uuid());try{
userService.register(user);
request.setAttribute("msg", "注册成功");
request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
}catch(UserException e) {
request.setAttribute("msg", e.getMessage());//将用户在注册表单中输入的信息保存在request域中,请求转发的register.jsp,目的回显
request.setAttribute("user", user);
request.getRequestDispatcher("/jsp/register.jsp").forward(request, response);
}
}public voidlogin(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {/*** 1、将用户登录表单中的信息封装成User对象
* 2、登录,如果发生异常,就转发到login.jsp页面,显示:异常信息
* 如果成功,就将查询到的user对象u,存放到session域中
* 然后转发到shopping.jsp页面,显示:欢迎用户登录*/User user= CommonsUtils.toBean(request.getParameterMap(), User.class);
System.out.println(user+"-------->");try{
User u=userService.login(user);
System.out.println(u+">>>>");//将u存放到session域中
request.getSession().setAttribute("user", u);
request.getRequestDispatcher("/jsp/index.jsp").forward(request, response);
}catch(UserException e) {
request.setAttribute("msg", e.getMessage());
request.setAttribute("user", user); //回显
request.getRequestDispatcher("/jsp/login.jsp").forward(request, response);
}
}
}