D07 Sping Boot 入门 Sping框架--Java Web之书城项目(二)实现用户登录功能
8、实现用户登录功能
1、获取请求的参数
2、调用XXXService.xxx()处理业务/userService.log()登录
3、根据login()方法返回结果判断登录是否成功
Ⅰ、成功
跳到登录成功页面
Ⅱ、失败
跳回登录页面
在com.gychen.web里新建LoginServlet类
1 package com.gychen.web; 2 3 import com.gychen.pojo.User; 4 import com.gychen.service.UserService; 5 import com.gychen.service.impl.UserServiceImpl; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 import java.io.IOException; 12 13 public class LoginServlet extends HttpServlet { 14 15 private UserService userService = new UserServiceImpl(); 16 @Override 17 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 19 // 1、获取请求的参数 20 String username = req.getParameter("username"); 21 String password = req.getParameter("password"); 22 23 // 2、调用XXXService.xxx()处理业务/userService.log()登录 24 //判断用户名是否存在 25 if(userService.existUsername(username)){ 26 // userService.login(new User(null,username,password,null)); 27 // 28 // 3、根据login()方法返回结果判断登录是否成功 29 if(userService.login(new User(null,username,password,null)) != null) { 30 // 31 // Ⅰ、成功 32 System.out.println("login success"); 33 // 34 // 跳到登录成功页面 35 req.getRequestDispatcher("/pages/user/login_success.html").forward(req,resp); 36 }else { 37 // 38 // Ⅱ、失败 39 System.out.println("login failed"); 40 // 41 // 跳回登录页面 42 req.getRequestDispatcher("/pages/user/login.html").forward(req,resp); 43 } 44 }else{ 45 System.out.println("用户名["+username+"]不存在,请先注册"); 46 // 跳回登录页面 47 req.getRequestDispatcher("/pages/user/login.html").forward(req,resp); 48 } 49 } 50 }