springboot 增加过滤器方法
2019-12-13 本文已影响0人
日落_3d9f
功能检测请求的接口中是否有版本号,检查版本号的对错,并返回正确的版本号。
自定义过滤器:
package com.ruoyi.fileter;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.shared.ApiRespResult;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
@WebFilter(filterName = "qcmappversion", urlPatterns = "/api/**")
public class MyFilter implements Filter {
private String appVersion = "1.0";
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("----------------------->过滤器被创建");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
System.out.println("--------------------->过滤器:请求地址"+httpServletRequest.getRequestURI());
//检查版本号
String qcmappversion = httpServletRequest.getHeader("qcmappversion");
if(qcmappversion == null) {
Map<String, String> map = new HashMap<>();
map.put("msg", "没有填写版本号");
map.put("code", "500");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.getWriter().print(JSONObject.toJSON(map));
return ;
} else if(!qcmappversion.equals(appVersion) ){
System.out.println("--------------------->版本号"+qcmappversion);
Map<String, String> map = new HashMap<>();
map.put("msg", "版本号错误,正确版本号为"+appVersion);
map.put("code", "501");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.getWriter().print(JSONObject.toJSON(map));
return ;
}
filterChain.doFilter(servletRequest, servletResponse);
return ;
}
@Override
public void destroy() {
System.out.println("----------------------->过滤器被销毁");
}
}
配置过滤器注入到spring容器:
package com.ruoyi.fileter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class WebConfiguration {
@Bean
public FilterRegistrationBean registerFilter() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());
registration.addUrlPatterns("/api/*");
registration.addInitParameter("paramName", "paramValue");
registration.setName("MyFilter");
registration.setOrder(1);
return registration;
}
}
此种方式配置可以实现自定义过滤URL的操作。
这里有文章实现了三种方式,可以参考:[【SpringBoot】RESTful API拦截-过滤器、拦截器、切片](https://blog.csdn.net/zlt995768025/article/details/80171789)