文章:
https://github.com/Snailclimb/springboot-guide/blob/master/docs/basis/springboot-filter.md
https://blog.csdn.net/weixin_39933264/article/details/100181291
demo源码:https://github.com/FDzhang/demo-study/tree/master/demo-springboot/demo-filter
2020-02-19
- 1 pom.xml 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
- 2 springboot的启动类添加注解
@ServletComponentScan
@SpringBootApplication
@ServletComponentScan
public class DemoFilterApplication {
public static void main(String[] args) {
SpringApplication.run(DemoFilterApplication.class, args);
}
}
- 3 简单使用
/**
* order(number) : 过滤器的顺序
* filterName : 过滤器名称
* urlPatterns : 需要过滤的路径
* initParams : 初始化参数,存于FilterConfig中
*/
@Order(1)
@WebFilter(filterName = "DemoFilter1", urlPatterns = "/*" , initParams = {})
public class DemoFilter1 implements Filter {
/**
* filter对象只会创建一次,init方法也只会执行一次。
*/
@Override
public void init(FilterConfig filterConfig) {
}
/**
* 主要的业务代码编写方法
*/
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
// 获取请求参数中的cityCode
String cityCode = request.getParameter("cityCode");
// 如果 cityCode==001 则通过
if ("001".equals(cityCode)){
// 放行
filterChain.doFilter(servletRequest,servletResponse);
}else {
// 返回错误信息
Map<String,Object> map = new HashMap<>(4);
map.put("code","301");
map.put("message","cityCode错误");
// 设置编码 和 数据格式
response.setCharacterEncoding("UTF-8");
response.setContentType("application/json; charset=utf-8");
Gson gson = new Gson();
response.getWriter().write(gson.toJson(map));
}
}
/**
* 在销毁Filter时自动调用。
*/
@Override
public void destroy() {
}
}