拦截器的使用
我们不能让客户通过地址栏来访问我们后台,必须通过登录才能访问后台。
1.隐藏登录的访问到后台的路径,将@RequestMapping("/user/login")路径跳转到main.html,但是不存在main.html。接下来实现第二步
@Controller
public class LoginController {
@RequestMapping("/user/login")
public String login(
@RequestParam("username") String username,
@RequestParam("password") String password,
Model model,
HttpSession session){
if(!StringUtils.isEmpty(username)&& "123456".equals(password)){
session.setAttribute("loginUser", username);
return "redirect:/main.html";
}else {
model.addAttribute("msg","用户名或密码错误");
return "index";
}
}
}
2.在自定义的mvc配置中田间main.html跳转
@Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("index");
registry.addViewController("/index.html").setViewName("index");
//dashboard是真实的跳转页面
registry.addViewController("/main.html").setViewName("dashboard");
}
3.创建拦截器,实现用户是否通过登录进入后台
public class LoginHandlerIntercepetor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//登录成功后,用户的session
Object loginUser = request.getSession().getAttribute("loginUser");
if(loginUser == null){
request.setAttribute("msg","没有权限,请先登录");
request.getRequestDispatcher("/index.html").forward(request,response);
return false;
}else{
return true;
}
}
}
4.注册拦截器组件
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LoginHandlerIntercepetor())
.addPathPatterns("/**")//拦截所有请求
.excludePathPatterns("/index.html","/user/login","/css/**","/js/**","/img/**","/");//给不需要拦截静态资源放行
}