**
拦截器
**
1.新建个类实现HandlerInterceptor接口
public class MyHandlerInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
Object username = request.getSession().getAttribute("username"); //获取session
if (username == null){//未登录,返回登录页面
request.setAttribute("msg","没有权限");
request.getRequestDispatcher("/index.html").forward(request,response); //跳转
return false;
}else {
//登录,放行
return true;
}
}
}
2.新建个类实现WebMvcConfigurer接口,继承实现addInterceptors方法。
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new MyHandlerInterceptor())
.addPathPatterns("/**") //所有都拦截
.excludePathPatterns("/","/index.html","/login","/css/**","/js/**","/img/**","/hello"); //放开的
}
session通过登陆成功后设置的
@RequestMapping("/login")
public String login(@RequestParam("username")String username,
@RequestParam("password")String password,
HttpSession session,
Model model){
User user = userService.selectPasswordByName(username, password);
if ( user != null){
//登录成功!
session.setAttribute("username",user.getUserName());
//登录成功!防止表单重复提交,我们重定向
return "redirect:/main.html";
}else {
//登录失败!存放错误信息
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}