javax.servlet.ServletContext#addFilter ( )源码实例Demo

下面列出了javax.servlet.ServletContext#addFilter ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: alf.io   文件: Initializer.java
@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);

}
 
/**
 * 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);
}
  }
 
源代码4 项目: alfresco-remote-api   文件: CORSContextListener.java
/**
 * Initializes CORS filter
 */
private void initCORS(ServletContext servletContext)
{
    WebApplicationContext wc = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);

    Properties gP = (Properties) wc.getBean(BEAN_GLOBAL_PROPERTIES);
    Boolean corsEnabled = new Boolean(gP.getProperty(CORS_ENABLED));

    if(logger.isDebugEnabled())
    {
        logger.debug("CORS filter is" + (corsEnabled?" ":" not ") + "enabled");
    }
    if (corsEnabled)
    {
        FilterRegistration.Dynamic corsFilter = servletContext.addFilter("CorsFilter", "org.apache.catalina.filters.CorsFilter");
        corsFilter.setInitParameter(CORS_ALLOWED_ORIGINS, gP.getProperty(CORS_ALLOWED_ORIGINS));
        corsFilter.setInitParameter(CORS_ALLOWED_METHODS, gP.getProperty(CORS_ALLOWED_METHODS));
        corsFilter.setInitParameter(CORS_ALLOWED_HEADERS, gP.getProperty(CORS_ALLOWED_HEADERS));
        corsFilter.setInitParameter(CORS_EXPOSED_HEADERS, gP.getProperty(CORS_EXPOSED_HEADERS));
        corsFilter.setInitParameter(CORS_SUPPORT_CREDENTIALS, gP.getProperty(CORS_SUPPORT_CREDENTIALS));
        corsFilter.setInitParameter(CORS_PREFLIGHT_CREDENTIALS, gP.getProperty(CORS_PREFLIGHT_CREDENTIALS));
        corsFilter.addMappingForUrlPatterns(DISPATCHER_TYPE, false, "/*");
    }
}
 
private void addDispatcherContext(ServletContext container) {
	// Create the dispatcher servlet's Spring application context
	AnnotationConfigWebApplicationContext dispatcherContext = new AnnotationConfigWebApplicationContext();
	dispatcherContext.register(SpringDispatcherConfig.class);

	// Declare <servlet> and <servlet-mapping> for the DispatcherServlet
	ServletRegistration.Dynamic dispatcher = container.addServlet("ch03-servlet",
			new DispatcherServlet(dispatcherContext));
	dispatcher.addMapping("*.html");
	dispatcher.setLoadOnStartup(1);

	FilterRegistration.Dynamic corsFilter = container.addFilter("corsFilter", new CorsFilter());
	corsFilter.setInitParameter("cors.allowed.methods", "GET, POST, HEAD, OPTIONS, PUT, DELETE");
	corsFilter.addMappingForUrlPatterns(null, true, "/*");

	FilterRegistration.Dynamic filter = container.addFilter("hiddenmethodfilter", new HiddenHttpMethodFilter());
	filter.addMappingForServletNames(null, true, "/*");

	FilterRegistration.Dynamic multipartFilter = container.addFilter("multipartFilter", new MultipartFilter());
	multipartFilter.addMappingForUrlPatterns(null, true, "/*");

}
 
源代码6 项目: microcks   文件: WebConfiguration.java
/** */
private void initCORSFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
   FilterRegistration.Dynamic corsFilter = servletContext.addFilter("corsFilter", new CorsFilter());
   corsFilter.addMappingForUrlPatterns(disps, true, "/api/*");
   corsFilter.addMappingForUrlPatterns(disps, true, "/dynarest/*");
   corsFilter.setAsyncSupported(true);
}
 
源代码7 项目: thorntail   文件: OpenTracingInitializer.java
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
    ServletContext servletContext = servletContextEvent.getServletContext();

    String skipPatternAttribute = servletContext.getInitParameter(TracingFilter.SKIP_PATTERN);
    if (null != skipPatternAttribute && !skipPatternAttribute.isEmpty()) {
        servletContext.setAttribute(TracingFilter.SKIP_PATTERN, Pattern.compile(skipPatternAttribute));
    }

    logger.info("Registering Tracing Filter");
    Dynamic filterRegistration = servletContext
        .addFilter("tracingFilter", new TracingFilter());
    filterRegistration.setAsyncSupported(true);
    filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "*");
}
 
源代码8 项目: flair-engine   文件: WebConfigurer.java
/**
 * Initializes the caching HTTP Headers Filter.
 */
private void initCachingHttpHeadersFilter(ServletContext servletContext,
                                          EnumSet<DispatcherType> disps) {
    log.debug("Registering Caching HTTP Headers Filter");
    FilterRegistration.Dynamic cachingHttpHeadersFilter =
        servletContext.addFilter("cachingHttpHeadersFilter",
            new CachingHttpHeadersFilter(jHipsterProperties));

    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/content/*");
    cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/app/*");
    cachingHttpHeadersFilter.setAsyncSupported(true);
}
 
@Override
public void onStartup(final Set<Class<?>> classes, final ServletContext servletContext) throws ServletException {
    if (servletContext.getMajorVersion() > 2 && servletContext.getEffectiveMajorVersion() > 2 &&
            !"true".equalsIgnoreCase(servletContext.getInitParameter(
                    Log4jWebSupport.IS_LOG4J_AUTO_INITIALIZATION_DISABLED
            ))) {
        final Logger LOGGER = StatusLogger.getLogger();

        LOGGER.debug("Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment.");

        final FilterRegistration.Dynamic filter =
                servletContext.addFilter("log4jServletFilter", Log4jServletFilter.class);
        if (filter == null) {
            LOGGER.warn("WARNING: In a Servlet 3.0+ application, you should not define a " +
                "log4jServletFilter in web.xml. Log4j 2 normally does this for you automatically. Log4j 2 " +
                "web auto-initialization has been canceled.");
            return;
        }

        final Log4jWebLifeCycle initializer = WebLoggerContextUtils.getWebLifeCycle(servletContext);
        initializer.start();
        initializer.setLoggerContext(); // the application is just now starting to start up

        servletContext.addListener(new Log4jServletContextListener());

        filter.setAsyncSupported(true); // supporting async when the user isn't using async has no downsides
        filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    }
}
 
源代码10 项目: component-runtime   文件: MdcInitializer.java
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) throws ServletException {
    try {
        ctx.getClassLoader().loadClass("org.apache.logging.log4j.web.ServletRequestThreadContext");
    } catch (final ClassNotFoundException e) {
        log.debug("log4j-web not available, skipping MDC setup");
        return;
    }
    final FilterRegistration.Dynamic filter = ctx.addFilter("mdc-request-binder", MdcRequestBinder.class);
    filter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), false, "/*");
    filter.setAsyncSupported(true);
}
 
源代码11 项目: thorntail   文件: OpenTracingContextInitializer.java
@Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
  ServletContext servletContext = servletContextEvent.getServletContext();
  Dynamic filterRegistration = servletContext
      .addFilter("tracingFilter", new SpanFinishingFilter());
  filterRegistration.setAsyncSupported(true);
  filterRegistration.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), false, "*");
}
 
源代码12 项目: flowable-engine   文件: WebConfigurer.java
/**
 * Initializes Spring Security.
 */
private void initSpringSecurity(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    LOGGER.debug("Registering Spring Security Filter");
    FilterRegistration.Dynamic springSecurityFilter = servletContext.addFilter("springSecurityFilterChain", new DelegatingFilterProxy());

    springSecurityFilter.addMappingForUrlPatterns(disps, false, "/*");
}
 
源代码13 项目: albedo   文件: WebConfigurer.java
/**
 * Initializes the caching HTTP Headers Filter.
 */
private void initCachingHttpHeadersFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
	log.debug("Registering Caching HTTP Headers Filter");
	FilterRegistration.Dynamic cachingHttpHeadersFilter = servletContext.addFilter("cachingHttpHeadersFilter",
		new CachingHttpHeadersFilter(applicationProperties));

	cachingHttpHeadersFilter.addMappingForUrlPatterns(disps, true, "/statics/*", "/WEB-INF/views/*");
	cachingHttpHeadersFilter.setAsyncSupported(true);

}
 
源代码14 项目: molgenis   文件: WebAppSecurityInitializer.java
@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, "*");
}
 
源代码15 项目: HttpSessionReplacer   文件: SessionHelpers.java
/**
 * Sets up servlet context - registers {@link SessionFilter} and {@link ShutdownListener}.
 *
 * @param context
 *          servlet context to set up
 */
static void setupContext(ServletContext context) {
  if (ServletLevel.isServlet3) {
    // When using Servlet 3.x+, we will register SessionFilter to make
    // sure session replacement is enabled
    Dynamic reg = context.addFilter("com.amdeus.session.filter", new SessionFilter());
    if (reg != null) {
      // The filter applies to all requests
      reg.addMappingForUrlPatterns(null, false, "/*");
    }
    // At the web app shutdown, we need to do some cleanup
    context.addListener(new ShutdownListener());
  }
}
 
源代码16 项目: piranha   文件: AuthenticationInitializer.java
/**
 * Initialize Eleos
 * 
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    
    // Gets the authentication module class that was configured externally
    Class<?> authModuleClass = (Class<?>) servletContext.getAttribute(AUTH_MODULE_CLASS);
    if (authModuleClass == null) {
        authModuleClass = DoNothingServerAuthModule.class;
    }
    
    String appContextId = servletContext.getVirtualServerName() + " " + servletContext.getContextPath();
    
    // This sets the authentication factory to the default factory. This factory stores and retrieves
    // the authentication artifacts.
    Security.setProperty(DEFAULT_FACTORY_SECURITY_PROPERTY, DefaultConfigFactory.class.getName());
    
    // Defines the modules that we have available. Here it's only a single fixed module.
    ConfigParser configParser = new DefaultConfigParser(authModuleClass);
    
    // Indicates the module we want to use
    Map<String, Object> options = new HashMap<>();
    options.put("authModuleId", authModuleClass.getSimpleName());
    
    // This authentication service installs an authentication config provider in the default factory, which
    // is the one we setup above. This authentication config provider uses the passed-in configParser to
    // retrieve configuration for authentication modules from.
    DefaultAuthenticationService authenticationService = new DefaultAuthenticationService(appContextId, options, configParser, null);
    
    servletContext.setAttribute(AUTH_SERVICE, authenticationService);
    
    servletContext.addFilter(AuthenticationFilter.class.getSimpleName(), AuthenticationFilter.class);
    
    // TMP - should use Dynamic
    ((WebApplication) servletContext).addFilterMapping(AuthenticationFilter.class.getSimpleName(), "/*");
}
 
源代码17 项目: spring-rest-server   文件: MyWebAppInitializer.java
private void addLoggingFilter(ServletContext container) {
    FilterRegistration.Dynamic fr = container.addFilter("loggingFilter", new CommonsRequestLoggingFilter());
    fr.addMappingForUrlPatterns(null, true, "/*");
}
 
源代码18 项目: maven-framework-project   文件: WebInitializer.java
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
	
	AnnotationConfigWebApplicationContext applicationContext = new AnnotationConfigWebApplicationContext();
	
	applicationContext.register(WebConfig.class);
	
	servletContext.addListener(new ContextLoaderListener(applicationContext));
	
	applicationContext.setServletContext(servletContext);
	
	FilterRegistration.Dynamic filter = servletContext.addFilter("characterEncodingFilter", org.springframework.web.filter.CharacterEncodingFilter.class);
	filter.setInitParameter("encoding", "utf-8");
	filter.setInitParameter("forceEncoding", "true");
	filter.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST), true, "/*");
	
	
	ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcherServlet", new DispatcherServlet(applicationContext));
	
	dispatcher.setLoadOnStartup(1);
	
	dispatcher.addMapping("/");
}
 
源代码19 项目: piranha   文件: AuthorizationPreInitializer.java
/**
 * Initialize Exousia
 *
 * @param classes the classes.
 * @param servletContext the Servlet context.
 * @throws ServletException when a Servlet error occurs.
 */
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
    WebApplication context = (WebApplication) servletContext;

    // Gets the authorization module classes that were configured externally
    Class<?> factoryClass = getAttribute(servletContext, AUTHZ_FACTORY_CLASS);
    Class<? extends Policy> policyClass = getAttribute(servletContext, AUTHZ_POLICY_CLASS);

    // Create the main Exousia authorization service, which implements the various entry points (an SPI)
    // for a runtime to make use of Jakarta Authorization
    AuthorizationService authorizationService = new AuthorizationService(
            factoryClass,
            policyClass, context.getServletContextId(),
            () -> localServletRequest.get(),
            () -> DefaultAuthenticatedIdentity.getCurrentSubject(),
            new PiranhaPrincipalMapper());

    // Join together in one list the constraints set by the servlet security elements, and the
    // piranha specific security constraint
    List<SecurityConstraint> securityConstraints = join(
            getConstraintsFromSecurityElements(servletContext, authorizationService),
            getConstraintsFromSecurityAnnotations(servletContext, authorizationService),
            getOptionalAttribute(servletContext, CONSTRAINTS),
            getConstraintsFromWebXMl(context));

    if (hasPermissionsSet(context)) {
        setPermissions(context, authorizationService);
    } else {
        authorizationService.addConstraintsToPolicy(
                securityConstraints != null ? securityConstraints : emptyList(),
                emptySet(),
                isDenyUncoveredHttpMethods(context),
                context.getServletRegistrations().keySet());
    }

    servletContext.setAttribute(AUTHZ_SERVICE, authorizationService);
    servletContext.addFilter(AuthorizationPreFilter.class.getSimpleName(), AuthorizationPreFilter.class);

    // TMP - should use Dynamic
    context.addFilterMapping(AuthorizationPreFilter.class.getSimpleName(), "/*");
}
 
源代码20 项目: openwebbeans-meecrowave   文件: CxfCdiAutoSetup.java
@Override
public void onStartup(final Set<Class<?>> c, final ServletContext ctx) {
    final Configuration builder = Configuration.class.cast(ctx.getAttribute("meecrowave.configuration"));
    final MeecrowaveCXFCdiServlet delegate = new MeecrowaveCXFCdiServlet();
    final FilterRegistration.Dynamic jaxrs = ctx.addFilter(NAME, new Filter() {
        private final String servletPath = builder.getJaxrsMapping().endsWith("/*") ?
                builder.getJaxrsMapping().substring(0, builder.getJaxrsMapping().length() - 2) : builder.getJaxrsMapping();

        @Override
        public void init(final FilterConfig filterConfig) throws ServletException {
            delegate.init(new ServletConfig() {
                @Override
                public String getServletName() {
                    return NAME;
                }

                @Override
                public ServletContext getServletContext() {
                    return filterConfig.getServletContext();
                }

                @Override
                public String getInitParameter(final String name) {
                    return filterConfig.getInitParameter(name);
                }

                @Override
                public Enumeration<String> getInitParameterNames() {
                    return filterConfig.getInitParameterNames();
                }
            });
        }

        @Override
        public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
            if (!HttpServletRequest.class.isInstance(request)) {
                chain.doFilter(request, response);
                return;
            }
            final HttpServletRequest http = HttpServletRequest.class.cast(request);
            final String path = http.getRequestURI().substring(http.getContextPath().length());
            final Optional<String> app = Stream.of(delegate.prefixes).filter(path::startsWith).findAny();
            if (app.isPresent()) {
                delegate.service(new HttpServletRequestWrapper(http) { // fake servlet pathInfo and path
                    @Override
                    public String getPathInfo() {
                        return path;
                    }

                    @Override
                    public String getServletPath() {
                        return servletPath;
                    }
                }, response);
            } else {
                chain.doFilter(request, response);
            }
        }

        @Override
        public void destroy() {
            delegate.destroy();
        }
    });
    jaxrs.setAsyncSupported(true);
    jaxrs.addMappingForUrlPatterns(EnumSet.of(DispatcherType.REQUEST, DispatcherType.ASYNC), true, builder.getJaxrsMapping());
    ofNullable(builder.getCxfServletParams()).ifPresent(m -> m.forEach(jaxrs::setInitParameter));
}