SpringBoot自定义Filter
SpringBoot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,当然我们可以自定
义Filter。
自定义Filter需要两个步骤:
【过滤打印请求URL】实例代码如下:
package xatu.zsl.Filter;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* Created by zsl on 2017/9/3.
*/
@Configuration
public class ConfigurationFilter {
@Bean
public RemoteIpFilter remoteIpFilter() {
return new RemoteIpFilter();
}
@Bean
public FilterRegistrationBean testFilterRegistration() {
FilterRegistrationBean registration = new FilterRegistrationBean();
registration.setFilter(new MyFilter());//添加过滤器
registration.addUrlPatterns("/*");//设置过滤路径,/*所有路径
registration.addInitParameter("name", "alue");//添加默认参数
registration.setName("MyFilter");//设置优先级
registration.setOrder(1);//设置优先级
return registration;
}
public class MyFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain
filterChain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) srequest;
//打印请求Url
System.out.println("this is MyFilter,url :" + request.getRequestURI());
filterChain.doFilter(srequest, sresponse);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
}
有人好奇public FilterRegistrationBean testFilterRegistration() 这个方法返回的FilterRegistrationBean如何在Coltroller中获取?,(●’◡’●),我很好奇,,于是乎!搞了点事情
在Controller中获取刚才ConfigurationFilter中【registration.addInitParameter(“name”, “alue”);//添加默认参数】这个设置的参数。
在Controller中加入如下代码就能获取(刚才【testFilterRegistration()】方法加了注解@Bean,所以Spring容器中会有一个实例, @Autowired就理所应当的注入进来了。)
@Autowired
FilterRegistrationBean registration;
@GetMapping("/getname")
public Map<String, String> getName() {
Map<String, String> initParameters = registration.getInitParameters();
return initParameters;
}