大家好:
本文簡單介紹一下用於權限控制的Spring boot攔截器配置,攔截器重定向問題。
開發工具:jdk1.8 idea2017(付費版,網上找的破解教程)
1,首先使用idea創建一個Spring boot+jsp的簡單項目,結構目錄如下:

2.創建filter文件夾,在文件夾創建CheckFilter.java文件,繼承攔截器基礎接口HandlerInterceptor,並實現以下三個方法:
preHandle:核心方法,請求處理器,只有該方法返回true,才會繼續執行后續的Controller。
postHandle:DispatcherServlet進行視圖返回渲染之前進行調用
afterCompletion:在DispatcherServlet 渲染了對應的視圖之后執行。用於進行資源清理

3,在filter文件中創建 WebMvcConfig.java文件,繼承類 WebMvcConfigurationSupport(攔截器的配置類,主要配置攔截器的相關參數),並繼承以下方法:
addInterceptors:添加攔截器實例
addResourceHandlers:靜態文件訪問配置
configureViewResolvers:視圖配置

4,最終代碼展示
攔截器
package com.example.filter; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckFilter implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("攔截器訪問方法:"+request.getServletPath()); 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 { } }
攔截器配置類
因為WebMvcConfigurationSupport不走自動化的配置文件,所以一些靜態文件,視圖配置需要自己手動再添加一下
package com.example.filter; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.*; @Configuration public class WebMvcConfig extends WebMvcConfigurationSupport { @Override protected void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new CheckFilter()).addPathPatterns("/**"). excludePathPatterns("/testBean/test"); super.addInterceptors(registry); } @Override protected void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/"); super.addResourceHandlers(registry); } @Override protected void configureViewResolvers(ViewResolverRegistry registry) { registry.jsp("/WEB-INF/",".jsp"); super.configureViewResolvers(registry); } }
addInterceptors(InterceptorRegistry registry):添加攔截器,並且配置攔截路徑等參數
addInterceptor(new CheckFilter()):添加實例化的攔截器
addPathPatterns("/**") :配置攔截器攔截的路徑
excludePathPatterns("/testBean/test"):配置不進去攔截器的方法,多少個就可以像這樣兒在后面一直添加,excludePathPatterns("/testBean/test","","",........).
ddResourceHandlers(ResourceHandlerRegistry registry):靜態文件訪問配置
onfigureViewResolvers(ViewResolverRegistry registry):試圖配置
測試的bean
package com.example.demo; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("testBean") public class TestBean { @RequestMapping("testDemo") public String TestDemo(){ return "hello"; } @RequestMapping("test") public String test(){ return "test"; } }
配置文件
#訪問相關配置 server.port=8080 server.tomcat.uri-encoding=UTF-8 #項目訪問名稱,如果不配置直接訪問bean就可以 server.servlet.context-path=/springBoot_demo #數據庫配置 spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver spring.datasource.url=jdbc:oracle:thin:@localhost:1521:ORCL spring.datasource.username=silver spring.datasource.password=silver #Spring boot視圖配置 spring.mvc.view.prefix=/WEB-INF/ spring.mvc.view.suffix=.jsp #靜態文件訪問配置 spring.mvc.static-path-pattern=/static/**
兩個簡單jsp
<%-- Created by IntelliJ IDEA. User: gen Date: 2018/7/25 Time: 17:34 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> Hello,World! </body> </html>
<%-- Created by IntelliJ IDEA. User: gen Date: 2018/8/23 Time: 16:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> 攔截器訪問! </body> </html>
4,開始測試代碼
打開瀏覽器訪問TestBean.java的第一方法
http://localhost:8080/springBoot_demo/testBean/testDemo


出現訪問攔截器的文字,測試成功
打開瀏覽器訪問TestBean.java的第二方法,這個方法配置不走攔截器
http://localhost:8080/springBoot_demo/testBean/test


如果進入攔截器應該會再多出現一行文字,沒有出現第二行字代表着測試成功,沒有進入攔截器
5.攔截器的重定向配置
關於這個重定向問題,在spring mvc中可以在攔截器中直接重定向到jsp中,例如這樣兒:response.sendRedirect(request.getContextPath()+"/mainFunction/errorMsg.jsp");
但是spring boot這樣寫會報錯,我在網上找了好多關於攔截器重定向文章,沒有發現直接訪問jsp的寫法,都是一個方案,直接重定向到bean的方法,然后返回到你想要頁面.
簡單修改代碼:
在CheckFilter.java的preHandle方法中添加兩行:
HttpSession seesion = request.getSession();
response.sendRedirect(request.getContextPath()+"/testBean/test");
在請求已經響應后創建seesion會后台報錯,所以需要添加獲取session,在請求結束前創建session
這個方案需要將/testBean/test配置為不進入攔截器,要不然就會是一個無限重定向的死循環。
因為上面我已經將/testBean/test加入到不進去攔截器的配置中,所以WebMvcConfig.java就不需要再改了
修改后代碼:
package com.example.filter; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class CheckFilter implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { System.out.println("攔截器訪問方法:"+request.getServletPath()); response.sendRedirect(request.getContextPath()+"/testBean/test"); 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 { } }
6.重啟項目,測試重定向是否生效
打開瀏覽器繼續訪問TestBean.java的第一方法
http://localhost:8080/springBoot_demo/testBean/testDemo

測試成功,正常進去test.jsp中
