标签:nts throws create control this ted .net override ext
SpringBoot自动添加了OrderedCharacterEncodingFilter和HiddenHttpMethodFilter,当然我们可以自定
义Filter。
自定义Filter需要两个步骤:
- 实现Filter【javax.servlet.Filter】接口,实现Filter方法
- 添加 @Configuration 注解,将自定义Filter加入过滤链
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 {
}
}
}
在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;
}
标签:nts throws create control this ted .net override ext
原文地址:https://www.cnblogs.com/jpfss/p/9070834.html