今天进行了登陆界面的实现,包括登陆注册,记住密码,验证码注册。
@WebServlet("/loginServlet") public class LoginServlet extends HttpServlet { private UserService service = new UserService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1接受用户名和密码 String username=request.getParameter("username"); String password = request.getParameter("password"); String remember = request.getParameter("remember"); User user = service.login(username, password); if (user !=null){ //登陆成功 //获取复选框数据 if ("1".equals(remember)){ //勾选,发送cookie //创建cookie, Cookie c_username=new Cookie("username",username); Cookie c_password=new Cookie("password",password); //设置存活时间 c_username.setMaxAge(60*60*24*7); c_password.setMaxAge(60*60*24*7); //2.发送 response.addCookie(c_username); response.addCookie(c_password); } //将user对象存储到session HttpSession session = request.getSession(); session.setAttribute("user",user); String contextPath = request.getContextPath(); response.sendRedirect(contextPath+"/selectAllServlet"); }else { //失败,跳转回 //存储错误信息到request request.setAttribute("login_mag","用户名或密码错误"); //跳转到login.jsp request.getRequestDispatcher("/login.jsp").forward(request,response); } }
@WebServlet("/registerServlet") public class RegisterServlet extends HttpServlet { private UserService service = new UserService(); @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String username=request.getParameter("username"); String password = request.getParameter("password"); User user =new User(); user.setUsername(username); user.setPassword(password); //获取用户输入的验证码 String checkCode = request.getParameter("checkCode"); //程序生成的验证码,从session HttpSession session = request.getSession(); String checkCodeGen = (String) session.getAttribute("checkCodeGen"); //比对 if(!checkCodeGen.equalsIgnoreCase(checkCode)){ request.setAttribute("register_mag","验证码错误"); request.getRequestDispatcher("/register.jsp").forward(request,response); //不允许注册 return; } //调用service注册 boolean register = service.register(user); //判断成功与否 if(register){ //成功,到登录页面 request.setAttribute("register_mag","注册成功,请登录"); request.getRequestDispatcher("/login.jsp").forward(request,response); }else { //失败,到注册页面 request.setAttribute("register_mag","用户名已存在"); request.getRequestDispatcher("/register.jsp").forward(request,response); } }
标签:username,String,记录,每日,request,user,password,response From: https://www.cnblogs.com/xiao-hong111/p/17386222.html