1.定義一個視圖解析器
@Configuration public class MyMvcConfig implements WebMvcConfigurer { /** * 添加視圖解析 */ //// 無用代碼,暫時注釋,之后刪除 // @Override // public void addViewControllers(ViewControllerRegistry registry) { // registry.addViewController("/").setViewName("index"); // registry.addViewController("/index.html").setViewName("index"); // registry.addViewController("/login.html").setViewName("login"); // registry.addViewController("/login").setViewName("login"); // registry.addViewController("/personal_center").setViewName("personal_center"); // } /** * 注冊攔截器 */ @Override public void addInterceptors(InterceptorRegistry registry) { // registry.addInterceptor(new LoginInterceptor()) // .addPathPatterns("/**").excludePathPatterns("/index","/","/login","/user/login","/static/**","/druid/*"); InterceptorRegistration addInterceptor = registry.addInterceptor(new LoginInterceptor()); // 排除配置 addInterceptor.excludePathPatterns("/index"); addInterceptor.excludePathPatterns("/login"); addInterceptor.excludePathPatterns("/"); addInterceptor.excludePathPatterns("/error"); addInterceptor.excludePathPatterns("/static/**"); addInterceptor.excludePathPatterns("/pdb/tuba/**"); addInterceptor.excludePathPatterns("/test/**"); // 攔截配置 addInterceptor.addPathPatterns("/**"); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); } }
2.定義一個攔截器
/** * 登錄攔截器 */ public class LoginInterceptor implements HandlerInterceptor { /** * 在請求處理之前進行調用(Controller方法調用之前) */ @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object object) throws ServletException, IOException { Object user = request.getSession().getAttribute("user"); if (user==null){ request.setAttribute("error","當前處於未登錄狀態!"); // request.getRequestDispatcher("/").forward(request,response); response.sendRedirect("/index"); return false; }else { return true; } } /** * 請求處理之后進行調用,但是在視圖被渲染之前(Controller方法調用之后) */ @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object object, ModelAndView mv) throws Exception { // TODO Auto-generated method stub } /** * 在整個請求結束之后被調用,也就是在DispatcherServlet 渲染了對應的視圖之后執行 * (主要是用於進行資源清理工作) */ @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object object, Exception ex) throws Exception { // TODO Auto-generated method stub } }
