最近项目中需要将请求中的header中增加几个字段,第一反应就是可不可以用拦截器拦截请求后将字段放进请求头中,经过网上一番学习后发现该方案可行,故将此方法记录下来供大家参考,也算是对自己学习成果的一个沉淀。
- 首先建一个拦截器类
-
package com.chwtest.filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebFilter; @WebFilter(filterName = "testFilter", urlPatterns = { "/testFilter" }) public class RequestFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void destroy() { Filter.super.destroy(); } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("拦截器生效"); chain.doFilter(request, response); } }
该类需要一个注解:@WebFilter ,并且需要实现 Filter 并重写doFilter方法
- 在启动类中增加注解:@ServletComponentScan
-
package com.chwtest; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.web.servlet.ServletComponentScan; @SpringBootApplication @ServletComponentScan @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }
- 新建一个controller
-
package com.chwtest.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class Controller { @RequestMapping("testFilter") public String testFilter(HttpServletRequest request) { return "hello word!"; } }
- 启动程序
-
至此拦截器已建好