(1)、編寫攔截器
1 package cn.coreqi.config; 2 3 import org.springframework.util.StringUtils; 4 import org.springframework.web.servlet.HandlerInterceptor; 5 6 import javax.servlet.http.HttpServletRequest; 7 import javax.servlet.http.HttpServletResponse; 8 import javax.servlet.http.HttpSession; 9 10 public class LoginHandlerInterceptor implements HandlerInterceptor { 11 12 //在目標方法執行之前運行此方法 13 @Override 14 public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { 15 HttpSession session = request.getSession(); 16 String loginUser = (String) session.getAttribute("loginUser"); 17 if(StringUtils.isEmpty(loginUser)){ 18 //說明用戶未登陸 19 request.setAttribute("msg","沒有相應權限請先登陸"); 20 request.getRequestDispatcher("/index.html").forward(request,response); 21 return false; 22 } 23 return true; 24 } 25 }
(2)、對攔截器進行注冊
1 package cn.coreqi.config; 2 3 import org.springframework.context.annotation.Bean; 4 import org.springframework.context.annotation.Configuration; 5 import org.springframework.web.servlet.LocaleResolver; 6 import org.springframework.web.servlet.config.annotation.*; 7 8 /** 9 * 擴展SpringMVC 10 * SpringBoot2使用的Spring5,因此將WebMvcConfigurerAdapter改為WebMvcConfigurer 11 * 使用WebMvcConfigurer擴展SpringMVC好處既保留了SpringBoot的自動配置,又能用到我們自己的配置 12 */ 13 //@EnableWebMvc //如果我們需要全面接管SpringBoot中的SpringMVC配置則開啟此注解, 14 //開啟后,SpringMVC的自動配置將會失效。 15 @Configuration 16 public class WebConfig implements WebMvcConfigurer { 17 @Override 18 public void addViewControllers(ViewControllerRegistry registry) { 19 //設置對“/”的請求映射到index 20 //如果沒有數據返回到頁面,沒有必要用控制器方法對請求進行映射 21 registry.addViewController("/").setViewName("index"); 22 } 23 24 //注冊攔截器 25 @Override 26 public void addInterceptors(InterceptorRegistry registry) { 27 //SpringMVC下,攔截器的注冊需要排除對靜態資源的攔截(*.css,*.js) 28 //SpringBoot已經做好了靜態資源的映射,因此我們無需任何操作 29 registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**") 30 .excludePathPatterns("/index.html","/","/user/login"); 31 } 32 }