一:login接口,密码和用户名正确后就request.getSession().setAttribute,直接上代码:
@RestController
@RequestMapping("/demo")
public class LoginController {
@PostMapping("/login")
public R login(@RequestBody Login login, HttpServletRequest request){
if(login.getUsername().equals("admin")&&login.getPassword().equals("admin")){
request.getSession().setAttribute("user", login);
return R.ok().message("成功登录");
}
return R.error();
}
@GetMapping("/test")
public R test(){
return R.ok().message("测试成功");
}
//清除session
@GetMapping("/remove")
public R remove(HttpServletRequest request){
request.getSession().removeAttribute("user");
return R.ok().message("清除session成功");
}
二:自定义拦截器类实现HandlerInterceptor接口
public class RequestInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("user");
if(user==null){
System.out.println("还没有登录,请进行登录,user="+user);
return false;
}else{
System.out.println("通过,已经登录,user="+user);
return true;
}
}
}
三:自定义拦截路径类实现WebMvcConfigurer接口
@Configuration
public class MyConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new RequestInterceptor()).addPathPatterns("/**").excludePathPatterns("/demo/login");
}
}
五:运行结果截图
运行remove接口后再运行test接口就会失败,因为已经清除session