思想:直接访问应用的主页面,如果没有登录则被拦截,重定向到登录界面。
1、创建登录拦截器
@Component
public class RemeberLoginIntercepter implements HandlerInterceptor {
@Autowired
private UserMapper userMapper;
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Cookie[] cookies = request.getCookies();//获取所有cookie信息
if(cookies == null) {//若没有cookie则去登录界面登录
System.out.println("cookie集合为null");
response.sendRedirect(request.getContextPath()+"/login.html");
return false;
}
for(Cookie c:cookies) {
System.out.println(c.getName()+"===="+c.getValue());
}
String cookieUsername = null;
for(Cookie item:cookies) {//遍历所有cookie,查找是否有名为cookie_username的cookie(找到不代表具有登录信息)
if(item.getName().equals("cookie_username")) {
System.out.println("cookiename==="+item.getName());
cookieUsername = item.getValue();//将cookie的内容赋值给字符串cookieUsername
break;
}
}
if(cookieUsername == "" || cookieUsername == null) {//如果cookie为空说明不具有登录信息
response.sendRedirect(request.getContextPath()+"/login.html");
return false;
}
//以上情况都没有,说明cookie中具有登录信息
HttpSession session = request.getSession();
Object userSession = session.getAttribute("user");//先查找session
if(userSession == null) {//若session为空,则已经过期,创建session
User u = userMapper.login(cookieUsername);
session.setAttribute("user",u);
}
return true;
}
}
2、注册登录拦截器
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Autowired
private RemeberLoginIntercepter remeberLoginIntercepter;
/*添加登录拦截器*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(remeberLoginIntercepter)
.addPathPatterns("/**")
.excludePathPatterns("/webjars/**",
"/v2/**","/swagger-resources/**","/swagger-ui.html",
"/css/**","/fonts/**","/images/**",
"/js/**","/user/doLogin.html","/login.html","/logout.html");
}
}
3、controller层
@ApiOperation("处理登录请求")
@PostMapping("/doLogin.html")
public String doLogin(@RequestParam("loginName") String loginName,
@RequestParam("userPwd") String userPwd, HttpSession session,
Model model, HttpServletRequest request, HttpServletResponse response) {
Msg msg = userService.login(loginName, userPwd,session,request,response);
if (msg.getStatus() == 200) {
model.addAttribute("fail", "");
return "redirect:/main.html";
} else {
model.addAttribute("fail", msg.getExtend().get("fail"));
return "login";
}
}
4、service层实现类
@Service
public class UserServiceImpl implements UserService {
@Autowired
UserMapper userMapper;
/*登录*/
@Override
public Msg login(String loginName, String userPwd, HttpSession session,
HttpServletRequest request, HttpServletResponse response) {
User u = userMapper.login(loginName);
if (u == null) {
return Msg.error().add("fail", "该用户不存在");
} else if (!u.getUserPassword().equals(userPwd)) {
return Msg.error().add("fail", "用户名密码错误");
} else {
session.setAttribute("user", u);
Cookie userCookie = new Cookie("cookie_username",u.getLoginName());//服务器创建cookie,存储内容为用户名
userCookie.setMaxAge(60*60*24);//设置cookie存在时间为一天
userCookie.setPath("/");//当前项目都携带这个cookie
response.addCookie(userCookie);//向客户端发送cookie
return Msg.success().add("succ", "登录成功").add("user",u);
}
}
}
5、注销登录
@ApiOperation("退出登录")
@GetMapping("/logout.html")
public String logout(HttpSession session,HttpServletResponse response,HttpServletRequest request) {
session.removeAttribute("user");
Cookie cookie = new Cookie("cookie_username","");
cookie.setMaxAge(0);
cookie.setPath("/");
response.addCookie(cookie);
return "redirect:/login.html";
}