下面列出了怎么用javax.servlet.FilterRegistration.Dynamic的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Add the given filter to the ServletContext and map it to the
* {@code DispatcherServlet} as follows:
* <ul>
* <li>a default filter name is chosen based on its concrete type
* <li>the {@code asyncSupported} flag is set depending on the
* return value of {@link #isAsyncSupported() asyncSupported}
* <li>a filter mapping is created with dispatcher types {@code REQUEST},
* {@code FORWARD}, {@code INCLUDE}, and conditionally {@code ASYNC} depending
* on the return value of {@link #isAsyncSupported() asyncSupported}
* </ul>
* <p>If the above defaults are not suitable or insufficient, override this
* method and register filters directly with the {@code ServletContext}.
* @param servletContext the servlet context to register filters with
* @param filter the filter to be registered
* @return the filter registration
*/
protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
String filterName = Conventions.getVariableName(filter);
Dynamic registration = servletContext.addFilter(filterName, filter);
if (registration == null) {
int counter = 0;
while (registration == null) {
if (counter == 100) {
throw new IllegalStateException("Failed to register filter with name '" + filterName + "'. " +
"Check if there is another filter registered under the same name.");
}
registration = servletContext.addFilter(filterName + "#" + counter, filter);
counter++;
}
}
registration.setAsyncSupported(isAsyncSupported());
registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());
return registration;
}
/**
* Add the given filter to the ServletContext and map it to the
* {@code DispatcherServlet} as follows:
* <ul>
* <li>a default filter name is chosen based on its concrete type
* <li>the {@code asyncSupported} flag is set depending on the
* return value of {@link #isAsyncSupported() asyncSupported}
* <li>a filter mapping is created with dispatcher types {@code REQUEST},
* {@code FORWARD}, {@code INCLUDE}, and conditionally {@code ASYNC} depending
* on the return value of {@link #isAsyncSupported() asyncSupported}
* </ul>
* <p>If the above defaults are not suitable or insufficient, override this
* method and register filters directly with the {@code ServletContext}.
* @param servletContext the servlet context to register filters with
* @param filter the filter to be registered
* @return the filter registration
*/
protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
String filterName = Conventions.getVariableName(filter);
Dynamic registration = servletContext.addFilter(filterName, filter);
if (registration == null) {
int counter = 0;
while (registration == null) {
if (counter == 100) {
throw new IllegalStateException("Failed to register filter with name '" + filterName + "'. " +
"Check if there is another filter registered under the same name.");
}
registration = servletContext.addFilter(filterName + "#" + counter, filter);
counter++;
}
}
registration.setAsyncSupported(isAsyncSupported());
registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());
return registration;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
Dynamic fr = servletContext.addFilter("org.springframework.security.web.access.intercept.FilterSecurityInterceptor#0", EmptyFilter.class);
if(fr!=null){
fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/fuckSpringBootFilterSecurityInterceptor");
fr.setAsyncSupported(true);
}
fr = servletContext.addFilter("org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter#0", EmptyFilter.class);
if(fr!=null){
fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/fuckSpringBootFilterSecurityInterceptor");
fr.setAsyncSupported(true);
}
fr = servletContext.addFilter("casFilter", EmptyFilter.class);
if(fr!=null){
fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), true, "/fuckSpringBootFilterSecurityInterceptor");
fr.setAsyncSupported(true);
}
}
/**
* Add the given filter to the ServletContext and map it to the
* {@code DispatcherServlet} as follows:
* <ul>
* <li>a default filter name is chosen based on its concrete type
* <li>the {@code asyncSupported} flag is set depending on the
* return value of {@link #isAsyncSupported() asyncSupported}
* <li>a filter mapping is created with dispatcher types {@code REQUEST},
* {@code FORWARD}, {@code INCLUDE}, and conditionally {@code ASYNC} depending
* on the return value of {@link #isAsyncSupported() asyncSupported}
* </ul>
* <p>If the above defaults are not suitable or insufficient, override this
* method and register filters directly with the {@code ServletContext}.
* @param servletContext the servlet context to register filters with
* @param filter the filter to be registered
* @return the filter registration
*/
protected FilterRegistration.Dynamic registerServletFilter(ServletContext servletContext, Filter filter) {
String filterName = Conventions.getVariableName(filter);
Dynamic registration = servletContext.addFilter(filterName, filter);
if (registration == null) {
int counter = -1;
while (counter == -1 || registration == null) {
counter++;
registration = servletContext.addFilter(filterName + "#" + counter, filter);
Assert.isTrue(counter < 100,
"Failed to register filter '" + filter + "'." +
"Could the same Filter instance have been registered already?");
}
}
registration.setAsyncSupported(isAsyncSupported());
registration.addMappingForServletNames(getDispatcherTypes(), false, getServletName());
return registration;
}
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
Thread.setDefaultUncaughtExceptionHandler(new DefaultExceptionHandler());
configureSessionCookie(servletContext);
CharacterEncodingFilter cef = new CharacterEncodingFilter();
cef.setEncoding("UTF-8");
cef.setForceEncoding(true);
Dynamic characterEncodingFilter = servletContext.addFilter("CharacterEncodingFilter", cef);
characterEncodingFilter.setAsyncSupported(true);
characterEncodingFilter.addMappingForUrlPatterns(null, false, "/*");
//force log initialization, then disable it
XRLog.setLevel(XRLog.EXCEPTION, Level.WARNING);
XRLog.setLoggingEnabled(false);
}
@Override public void init(ServletContextHandler handler) {
AnnotationConfigWebApplicationContext appContext =
new AnnotationConfigWebApplicationContext() {
// overriding this allows us to register dependencies of TracingHandlerInterceptor
// without passing static state to a configuration class.
@Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) {
beanFactory.registerSingleton("httpTracing", httpTracing);
super.loadBeanDefinitions(beanFactory);
}
};
appContext.register(Servlet3TestController.class); // the test resource
appContext.register(TracingConfig.class); // generic tracing setup
DispatcherServlet servlet = new DispatcherServlet(appContext);
servlet.setDispatchOptionsRequest(true);
ServletHolder servletHolder = new ServletHolder(servlet);
servletHolder.setAsyncSupported(true);
handler.addServlet(servletHolder, "/*");
handler.addEventListener(new ContextLoaderListener(appContext));
// add the trace filter, which lazy initializes a real tracing filter from the spring context
Dynamic filterRegistration =
handler.getServletContext().addFilter("tracingFilter", DelegatingTracingFilter.class);
filterRegistration.setAsyncSupported(true);
filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
private void handleFilter(FilterConfiguration filter,ServletContext webappContext){
filter.getFilter().fold(clazz-> {
setInitParameters(webappContext.addFilter(getName(filter),
clazz), filter)
.addMappingForUrlPatterns(
EnumSet.allOf(DispatcherType.class),true,
filter.getMapping());
return 1;
}, obj-> {
Dynamic filterReg = webappContext.addFilter(
getName(filter), obj);
filterReg.addMappingForUrlPatterns(
EnumSet.allOf(DispatcherType.class),true,
filter.getMapping());
return 2;
});
}
private void addExplicitlyDeclaredFilters(ServletContext webappContext) {
for (FilterData filterData : filterData) {
Dynamic filterReg = webappContext.addFilter(
filterData.getFilterName(), filterData.getFilter());
filterReg.addMappingForUrlPatterns(
EnumSet.allOf(DispatcherType.class),true,
filterData.getMapping());
logFilter(filterData);
}
}
/**
* Register a {@link DispatcherServlet} against the given servlet context.
* <p>This method will create a {@code DispatcherServlet} with the name returned by
* {@link #getServletName()}, initializing it with the application context returned
* from {@link #createServletApplicationContext()}, and mapping it to the patterns
* returned from {@link #getServletMappings()}.
* <p>Further customization can be achieved by overriding {@link
* #customizeRegistration(ServletRegistration.Dynamic)} or
* {@link #createDispatcherServlet(WebApplicationContext)}.
* @param servletContext the context to register the servlet against
*/
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty");
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext, "createServletApplicationContext() must not return null");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
Assert.notNull(dispatcherServlet, "createDispatcherServlet(WebApplicationContext) must not return null");
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
if (registration == null) {
throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
"Check if there is another servlet registered under the same name.");
}
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
if (servlets.containsKey(servletName)) {
return null;
}
servlets.put(servletName, servlet);
MockServletRegistration registration = new MockServletRegistration();
servletRegistrations.put(servletName, registration);
return registration;
}
@Override
public Dynamic addFilter(String filterName, Filter filter) {
if (filters.containsKey(filterName)) {
return null;
}
filters.put(filterName, filter);
MockFilterRegistration registration = new MockFilterRegistration();
filterRegistrations.put(filterName, registration);
return registration;
}
/**
* Register a {@link DispatcherServlet} against the given servlet context.
* <p>This method will create a {@code DispatcherServlet} with the name returned by
* {@link #getServletName()}, initializing it with the application context returned
* from {@link #createServletApplicationContext()}, and mapping it to the patterns
* returned from {@link #getServletMappings()}.
* <p>Further customization can be achieved by overriding {@link
* #customizeRegistration(ServletRegistration.Dynamic)} or
* {@link #createDispatcherServlet(WebApplicationContext)}.
* @param servletContext the context to register the servlet against
*/
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return null or empty");
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext, "createServletApplicationContext() must not return null");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
Assert.notNull(dispatcherServlet, "createDispatcherServlet(WebApplicationContext) must not return null");
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
if (registration == null) {
throw new IllegalStateException("Failed to register servlet with name '" + servletName + "'. " +
"Check if there is another servlet registered under the same name.");
}
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
if (servlets.containsKey(servletName)) {
return null;
}
servlets.put(servletName, servlet);
MockServletRegistration registration = new MockServletRegistration();
servletRegistrations.put(servletName, registration);
return registration;
}
@Override
public Dynamic addFilter(String filterName, Filter filter) {
if (filters.containsKey(filterName)) {
return null;
}
filters.put(filterName, filter);
MockFilterRegistration registration = new MockFilterRegistration();
filterRegistrations.put(filterName, registration);
return registration;
}
private void configureCors(Environment environment) {
Dynamic filter = environment.servlets().addFilter("CORS", CrossOriginFilter.class);
filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
filter.setInitParameter(CrossOriginFilter.ALLOWED_METHODS_PARAM, "GET,PUT,POST,DELETE,OPTIONS");
filter.setInitParameter(CrossOriginFilter.ALLOWED_ORIGINS_PARAM, "*");
filter.setInitParameter(CrossOriginFilter.ACCESS_CONTROL_ALLOW_ORIGIN_HEADER, "*");
filter.setInitParameter("allowedHeaders", "Content-Type,Authorization,X-Requested-With,Content-Length,Accept,Origin");
filter.setInitParameter("allowCredentials", "true");
}
/**
* Registers the provided filter using the {@link #isAsyncSessionSupported()} and
* {@link #getSessionDispatcherTypes()}.
* @param servletContext the servlet context
* @param insertBeforeOtherFilters should this Filter be inserted before or after
* other {@link Filter}
* @param filterName the filter name
* @param filter the filter
*/
private void registerFilter(ServletContext servletContext, boolean insertBeforeOtherFilters, String filterName,
Filter filter) {
Dynamic registration = servletContext.addFilter(filterName, filter);
if (registration == null) {
throw new IllegalStateException("Duplicate Filter registration for '" + filterName
+ "'. Check to ensure the Filter is only configured once.");
}
registration.setAsyncSupported(isAsyncSessionSupported());
EnumSet<DispatcherType> dispatcherTypes = getSessionDispatcherTypes();
registration.addMappingForUrlPatterns(dispatcherTypes, !insertBeforeOtherFilters, "/*");
}
protected void registeredHiddenMethodFilter(ServletContext servletContext, Class<? extends Filter> hiddenFilterClass){
Optional.ofNullable(hiddenFilterClass).ifPresent(cls->{
Dynamic fr = servletContext.addFilter(hiddenFilterClass.getSimpleName(), hiddenFilterClass);
Optional.ofNullable(fr).ifPresent(frconfig->{
// fr.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "/*");
// fr.addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, AbstractDispatcherServletInitializer.DEFAULT_SERVLET_NAME);
fr.setAsyncSupported(true);
fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), isMatchAfter, "/*");
// .addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
logger.info("FilterInitializer: {} has bean registered!", hiddenFilterClass.getSimpleName());
});
});
}
@Override public void init(ServletContextHandler handler) {
handler.getServletContext()
.addFilter("tracingFilter", TracingFilter.create(httpTracing))
.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
Dynamic sparkFilter = handler.getServletContext().addFilter("sparkFilter", new SparkFilter());
sparkFilter.setInitParameter("applicationClass", TestApplication.class.getName());
sparkFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
protected void registeredInitFilter(ServletContext servletContext, Class<? extends Filter> initFilterClass){
logger.info("registeredInitFilter: {} ", initFilterClass);
Optional.ofNullable(initFilterClass).ifPresent(cls->{
logger.info("execute registeredInitFilter ...");
Dynamic initfr = servletContext.addFilter("systemFilter", cls);
initfr.addMappingForUrlPatterns(this.getAllDispatcherTypes(), isMatchAfter, "/*");
initfr.setAsyncSupported(true);
initfr.setInitParameter("filterSuffix", "true");
logger.info("registeredInitFilter result: {} has bean registered!", initFilterClass.getSimpleName());
});
}
@Override
protected void beforeSpringSecurityFilterChain(ServletContext servletContext) {
// add filters
Dynamic forwardedHeaderFilter =
servletContext.addFilter("forwardedHeaderFilter", ForwardedHeaderFilter.class);
forwardedHeaderFilter.setAsyncSupported(true);
forwardedHeaderFilter.addMappingForUrlPatterns(EnumSet.of(REQUEST, ERROR, ASYNC), false, "*");
}
@Override
public void contextInitialized(ServletContextEvent sce) {
this.instance = createHazelcastInstance();
Map<String, Session> sessions = this.instance.getMap(SESSION_MAP_NAME);
MapSessionRepository sessionRepository = new MapSessionRepository(sessions);
SessionRepositoryFilter<? extends Session> filter = new SessionRepositoryFilter<>(sessionRepository);
Dynamic fr = sce.getServletContext().addFilter("springSessionFilter", filter);
fr.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
}
@Override public void init(ServletContextHandler handler) {
ResourceConfig config = new ResourceConfig();
config.register(new TestResource(httpTracing));
config.register(SpanCustomizingApplicationEventListener.create());
handler.addServlet(new ServletHolder(new ServletContainer(config)), "/*");
// add the underlying servlet tracing filter which the event listener decorates with more tags
Dynamic filterRegistration =
handler.getServletContext().addFilter("tracingFilter", TracingFilter.create(httpTracing));
filterRegistration.setAsyncSupported(true);
// isMatchAfter=true is required for async tests to pass!
filterRegistration.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
}
@Test
public void testDefault() throws ServletException {
InitializeSessionManagement ism = new InitializeSessionManagement();
Set<Class<?>> classes = Collections.emptySet();
ServletContext context = mock(ServletContext.class);
Dynamic dynamic = mock(Dynamic.class);
when(context.addFilter(any(String.class), any(Filter.class))).thenReturn(dynamic);
when(context.getClassLoader()).thenReturn(this.getClass().getClassLoader());
ism.onStartup(classes, context);
verify(context).addFilter(eq("com.amdeus.session.filter"), any(SessionFilter.class));
}
protected void registeredEncodingFilter(ServletContext servletContext, Class<? extends Filter> encodingFilterClass){
Optional.ofNullable(encodingFilterClass).ifPresent(cls->{
Dynamic fr = servletContext.addFilter("characterEncodingFilter", encodingFilterClass);
Optional.ofNullable(fr).ifPresent(frconfig->{
frconfig.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD), isMatchAfter, "/*");
frconfig.setAsyncSupported(true);
frconfig.setInitParameters(ImmutableMap.of("encoding", "UTF-8", "forceEncoding", "true"));
logger.info("FilterInitializer: {} has bean registered!", encodingFilterClass.getSimpleName());
});
});
}
/**
* Register a {@link DispatcherServlet} against the given servlet context.
* <p>This method will create a {@code DispatcherServlet} with the name returned by
* {@link #getServletName()}, initializing it with the application context returned
* from {@link #createServletApplicationContext()}, and mapping it to the patterns
* returned from {@link #getServletMappings()}.
* <p>Further customization can be achieved by overriding {@link
* #customizeRegistration(ServletRegistration.Dynamic)} or
* {@link #createDispatcherServlet(WebApplicationContext)}.
* @param servletContext the context to register the servlet against
*/
protected void registerDispatcherServlet(ServletContext servletContext) {
String servletName = getServletName();
Assert.hasLength(servletName, "getServletName() must not return empty or null");
WebApplicationContext servletAppContext = createServletApplicationContext();
Assert.notNull(servletAppContext,
"createServletApplicationContext() did not return an application " +
"context for servlet [" + servletName + "]");
FrameworkServlet dispatcherServlet = createDispatcherServlet(servletAppContext);
dispatcherServlet.setContextInitializers(getServletApplicationContextInitializers());
ServletRegistration.Dynamic registration = servletContext.addServlet(servletName, dispatcherServlet);
Assert.notNull(registration,
"Failed to register servlet with name '" + servletName + "'." +
"Check if there is another servlet registered under the same name.");
registration.setLoadOnStartup(1);
registration.addMapping(getServletMappings());
registration.setAsyncSupported(isAsyncSupported());
Filter[] filters = getServletFilters();
if (!ObjectUtils.isEmpty(filters)) {
for (Filter filter : filters) {
registerServletFilter(servletContext, filter);
}
}
customizeRegistration(registration);
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName, Servlet servlet) {
if (servlets.containsKey(servletName)) {
return null;
}
servlets.put(servletName, servlet);
MockServletRegistration registration = new MockServletRegistration();
servletRegistrations.put(servletName, registration);
return registration;
}
@Override
public Dynamic addFilter(String filterName, Filter filter) {
if (filters.containsKey(filterName)) {
return null;
}
filters.put(filterName, filter);
MockFilterRegistration registration = new MockFilterRegistration();
filterRegistrations.put(filterName, registration);
return registration;
}
@Override
public FilterRegistration.Dynamic addFilter(String filterName,
String className) {
return null;
}
@Override
public ServletRegistration.Dynamic addServlet(String servletName,
String className) {
return null;
}
@Override
public Dynamic addFilter(String filterName, Filter filter) {
return null;
}