以判断用户是否登陆为例使用拦截器进行拦截
第一步:
在登陆后立即把账号名存在Session中,以下为简单代码示例
@Controller
public class LoginController {
// @RequestMapping(value = "/user/login",method = RequestMethod.POST)
@PostMapping("/user/login")
public String login(@RequestParam("username") String username,
@RequestParam("password") String password,
Map<String,Object> map, HttpSession session)
{
if(!username.isEmpty()&&"123456".equals(password)){
//登陆成功,为了防止重复提交表单,可以重定向到主页
session.setAttribute("loginUser",username);
map.put("msg","登陆成功");
return "redirect:/main.html";
}else{
//登陆失败
map.put("msg","用户名密码错误");
return "login.html";
}
}
}
第二步:
重新编写拦截器组件,如下代码示例
重新写的的这个组件的主要作用是在Controller响应前,执行获取Session中数据,判断是否已经登陆。
public class LoginHandlerInterceptor implements HandlerInterceptor {
//目标方法执行前
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object user = request.getSession().getAttribute("loginUser");
if(user == null){
//未登陆,返回登陆页面
request.setAttribute("msg","没有权限,请先登陆");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
//已登陆 ,放行请求
return true;
}
}
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
}
}
第三步:
扩展SpringMVC的功能,重写配置类原有的方法addInterceptors把自己写的拦截器加进去,如下示例
排除登陆页面和登陆按钮还有静态资源的URL
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {
//浏览器发送请求到
@Override
public void addViewControllers(ViewControllerRegistry registry){
registry.addViewController("/fanren01").setViewName("success");
}
@Override
public void addInterceptors(InterceptorRegistry registry){
//拦截任意多层路径下的任意请求,排除(登陆页面,登陆请求,静态资源,bootstrap`jquery)
//springboot已经处理好了静态资源映射,不需要我们来处理
registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**")
.excludePathPatterns("/index.html","/","/index","/user/login",
"/asserts/**","/webjars/**");
}
}
那么结果就是只能先范围index登陆页,只有登陆之后拦截器能够在Session中获取账号名才会放行然后打开项目的其他页面