Example usage for javax.servlet ServletContext addFilter

List of usage examples for javax.servlet ServletContext addFilter

Introduction

In this page you can find the example usage for javax.servlet ServletContext addFilter.

Prototype

public FilterRegistration.Dynamic addFilter(String filterName, Class<? extends Filter> filterClass);

Source Link

Document

Adds the filter with the given name and class type to this servlet context.

Usage

From source file:org.brutusin.rpc.RpcWebInitializer.java

public void onStartup(final ServletContext ctx) throws ServletException {
    final RpcServlet rpcServlet = registerRpcServlet(ctx);
    final WebsocketFilter websocketFilter = new WebsocketFilter();
    FilterRegistration.Dynamic dynamic = ctx.addFilter(WebsocketFilter.class.getName(), websocketFilter);
    dynamic.addMappingForUrlPatterns(null, false, RpcConfig.getInstance().getPath() + "/wskt");
    JsonCodec.getInstance().registerStringFormat(MetaDataInputStream.class, "inputstream");
    final Bean<RpcSpringContext> rpcCtxBean = new Bean<RpcSpringContext>();
    ctx.addListener(new ServletRequestListener() {

        public void requestDestroyed(ServletRequestEvent sre) {
            GlobalThreadLocal.clear();//from   w ww .j a v a 2s.co m
        }

        public void requestInitialized(ServletRequestEvent sre) {
            GlobalThreadLocal.set(new GlobalThreadLocal((HttpServletRequest) sre.getServletRequest(), null));
        }
    });
    ctx.addListener(new ServletContextListener() {

        public void contextInitialized(ServletContextEvent sce) {
            RpcSpringContext rpcCtx = createRpcSpringContext(ctx);
            rpcCtxBean.setValue(rpcCtx);
            rpcServlet.setRpcCtx(rpcCtx);
            initWebsocketRpcRuntime(ctx, rpcCtx);
            ctx.setAttribute(RpcSpringContext.class.getName(), rpcCtx);
        }

        public void contextDestroyed(ServletContextEvent sce) {
            LOGGER.info("Destroying RPC context");
            if (rpcCtxBean.getValue() != null) {
                rpcCtxBean.getValue().destroy();
            }
        }
    });
    ctx.addListener(new ServletContextAttributeListener() {
        public void attributeAdded(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeRemoved(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        public void attributeReplaced(ServletContextAttributeEvent event) {
            if (event.getName().equals(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE)) {
                updateRootContext();
            }
        }

        private void updateRootContext() {
            WebApplicationContext rootCtx = WebApplicationContextUtils.getWebApplicationContext(ctx);
            if (rootCtx != null) {
                if (rpcCtxBean.getValue() != null) {
                    rpcCtxBean.getValue().setParent(rootCtx);
                }
                if (rootCtx.containsBean("springSecurityFilterChain")) {
                    LOGGER.info("Moving WebsocketFilter behind springSecurityFilterChain");
                    websocketFilter.disable();
                    FilterChainProxy fcp = (FilterChainProxy) rootCtx.getBean("springSecurityFilterChain");
                    fcp.getFilterChains().get(0).getFilters().add(new WebsocketFilter());
                }
            }
        }
    });
}

From source file:org.davidmendoza.demo.config.StartUpConfig.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.register(ComponentConfig.class, DataConfig.class, MailConfig.class, WebConfig.class);
    context.setDisplayName("DemoApp");

    FilterRegistration.Dynamic sitemeshFilter = servletContext.addFilter("sitemeshFilter",
            new ConfigurableSiteMeshFilter());
    sitemeshFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");

    FilterRegistration.Dynamic characterEncodingFilter = servletContext.addFilter("characterEncodingFilter",
            new CharacterEncodingFilter());
    characterEncodingFilter.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "/*");
    characterEncodingFilter.setInitParameter("encoding", "UTF-8");
    characterEncodingFilter.setInitParameter("forceEncoding", "true");

    servletContext.addListener(new ContextLoaderListener(context));
    //servletContext.setInitParameter("defaultHtmlEscape", "false");

    DispatcherServlet servlet = new DispatcherServlet();
    // no explicit configuration reference here: everything is configured in the root container for simplicity
    servlet.setContextConfigLocation("");

    ServletRegistration.Dynamic appServlet = servletContext.addServlet("appServlet", servlet);
    appServlet.setLoadOnStartup(1);/*from w w  w .j av a2s  .c o  m*/
    appServlet.setAsyncSupported(true);

    Set<String> mappingConflicts = appServlet.addMapping("/");
    if (!mappingConflicts.isEmpty()) {
        throw new IllegalStateException("'appServlet' cannot be mapped to '/' under Tomcat versions <= 7.0.14");
    }
}

From source file:org.obiba.mica.config.WebConfiguration.java

/**
 * Initializes the caching HTTP Headers Filter.
 *//*from w w  w  .  j  ava 2  s  .  c o m*/
private void initCachingHttpHeadersFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {
    log.debug("Registering Caching HTTP Headers Filter");
    FilterRegistration.Dynamic cachingFilter = servletContext.addFilter("cachingHttpHeadersFilter",
            new CachingHttpHeadersFilter());

    cachingFilter.addMappingForUrlPatterns(disps, true, "/images/*");
    cachingFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
    cachingFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
    cachingFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
    cachingFilter.setAsyncSupported(true);
}

From source file:org.obiba.mica.config.WebConfiguration.java

/**
 * Initializes the static resources production Filter.
 *///from   www. j av a 2s  .  c o  m
private void initStaticResourcesProductionFilter(ServletContext servletContext, EnumSet<DispatcherType> disps) {

    log.debug("Registering static resources production Filter");
    FilterRegistration.Dynamic resourcesFilter = servletContext.addFilter("staticResourcesProductionFilter",
            new StaticResourcesProductionFilter());

    resourcesFilter.addMappingForUrlPatterns(disps, true, "/favicon.ico");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/robots.txt");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/index.html");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/images/*");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/fonts/*");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/scripts/*");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/styles/*");
    resourcesFilter.addMappingForUrlPatterns(disps, true, "/views/*");
    resourcesFilter.setAsyncSupported(true);
}

From source file:org.unidle.config.DispatcherServletInitializer.java

@Override
public void onStartup(final ServletContext servletContext) throws ServletException {
    super.onStartup(servletContext);

    servletContext.setSessionTrackingModes(EnumSet.of(COOKIE));

    final DelegatingFilterProxy wroFilter = servletContext.createFilter(DelegatingFilterProxy.class);
    wroFilter.setTargetFilterLifecycle(true);
    wroFilter.setBeanName("wroFilter");

    servletContext.addFilter("wroFilter", wroFilter).addMappingForUrlPatterns(null, false, "/resources/*");

}

From source file:com.olegchir.wicket_spring_security_example.init.AppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {

    //Create webapp context
    AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext(); //part of spring-web
    root.register(SpringSecurityConfiguration.class); //register class by annotation. Here be all security rules.

    //Register DelegatingFilterProxy
    FilterRegistration.Dynamic springSecurityFilterChainReg = servletContext
            .addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);
    springSecurityFilterChainReg// w  w  w.j  av  a2s.c  o  m
            .addMappingForUrlPatterns(EnumSet.of(DispatcherType.ERROR, DispatcherType.REQUEST), false, "/*");

    servletContext.addListener(new ContextLoaderListener(root));

    //Register WicketFilter
    WicketFilter wicketFilter = new WicketFilter(new WicketApplication()) {
        @Override
        public void init(boolean isServlet, FilterConfig filterConfig) throws ServletException {
            setFilterPath(""); //don't use web.xml. WicketApplication.init is a custom override for it.
            super.init(isServlet, filterConfig);
        }
    };
    FilterRegistration.Dynamic wicketFilterReg = servletContext.addFilter("wicketFilter", wicketFilter);
    wicketFilterReg.addMappingForUrlPatterns(EnumSet.allOf(DispatcherType.class), true, "*");
}

From source file:com.devnexus.ting.web.WebAppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    servletContext.setInitParameter("javax.servlet.jsp.jstl.fmt.localizationContext", "messages");

    //UrlRewriteFilter
    final FilterRegistration.Dynamic urlRewriteFilterRegistration = servletContext.addFilter("UrlRewriteFilter",
            new UrlRewriteFilter());
    urlRewriteFilterRegistration.setAsyncSupported(true);
    urlRewriteFilterRegistration.addMappingForUrlPatterns(null, true, "/proxy/*");

    // UTF-8 Encoding
    FilterRegistration.Dynamic encodingFilterRegistration = servletContext.addFilter("encodingFilter",
            new CharacterEncodingFilter());
    encodingFilterRegistration.setInitParameter("encoding", "UTF-8");
    encodingFilterRegistration.setInitParameter("forceEncoding", "true");
    encodingFilterRegistration.addMappingForUrlPatterns(null, true, "/s/*");

    FilterRegistration.Dynamic gzipFilterRegistration = servletContext.addFilter("gzipFilter",
            CompressingFilter.class);
    gzipFilterRegistration.addMappingForUrlPatterns(null, true, "/s/*", "*.html", "/api/*");

    // jsonPRequestFilter
    FilterRegistration.Dynamic jsonPRequestFilterRegistration = servletContext.addFilter("JSONPRequestFilter",
            JSONPRequestFilter.class);
    jsonPRequestFilterRegistration.addMappingForUrlPatterns(null, true, "*.json");

    // lazyLoadingFilter
    FilterRegistration.Dynamic lazyLoadingFilterRegistration = servletContext.addFilter("lazyLoadingFilter",
            OpenEntityManagerInViewFilter.class);
    lazyLoadingFilterRegistration.addMappingForUrlPatterns(null, true, "*.html", "/s/*");

    // springSecurityFilterChain
    FilterRegistration.Dynamic springSecurityFilterChainRegistration = servletContext
            .addFilter("springSecurityFilterChain", DelegatingFilterProxy.class);
    springSecurityFilterChainRegistration.addMappingForUrlPatterns(null, true, "/*");

    // loggingFilter4Logback
    FilterRegistration.Dynamic loggingFilter4LogbackRegistration = servletContext
            .addFilter("loggingFilter4Logback", LoggingFilter4Logback.class);
    loggingFilter4LogbackRegistration.addMappingForUrlPatterns(null, true, "/s/*", "/api/*");

    // etagFilter
    FilterRegistration.Dynamic etagFilterRegistration = servletContext.addFilter("etagFilter",
            ShallowEtagHeaderFilter.class);
    etagFilterRegistration.addMappingForUrlPatterns(null, true, "/s/*");

    // sitemeshFilter
    FilterRegistration.Dynamic sitemeshRegistration = servletContext.addFilter("sitemesh",
            ConfigurableSiteMeshFilter.class);
    sitemeshRegistration.addMappingForUrlPatterns(null, true, "/s/*", "/index.jsp");

    // responseAddHttpHeadersFilter
    FilterRegistration.Dynamic responseAddHttpHeadersFilterRegistration = servletContext
            .addFilter("responseAddHttpHeadersFilter", ResponseAddHttpHeadersFilter.class);
    responseAddHttpHeadersFilterRegistration.setInitParameter("secondsToCache", "2592000");
    responseAddHttpHeadersFilterRegistration.addMappingForUrlPatterns(null, true, "*.css", "*.gif", "*.ico",
            "*.jpg", "*.png", "*.js");

    setupContext(servletContext);//from w  w  w  . j  a  va 2s  .  c  o m
    super.onStartup(servletContext);
}

From source file:com.sentinel.config.WebAppInitializer.java

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    LOG.trace("Method: onStartup called.");

    EnumSet<DispatcherType> dispatch = EnumSet.of(DispatcherType.REQUEST);
    super.onStartup(servletContext);
    DelegatingFilterProxy filter = new DelegatingFilterProxy("springSecurityFilterChain");
    filter.setContextAttribute("org.springframework.web.servlet.FrameworkServlet.CONTEXT.dispatcher");
    servletContext.addFilter("springSecurityFilterChain", filter).addMappingForUrlPatterns(dispatch, false,
            "/*");

    LOG.trace("Method: onStartup finished.");
}

From source file:com.rockagen.gnext.main.BootStrap.java

protected void addFilter(final ServletContext ctx) {

    AccessFilter af = (AccessFilter) rootContext.getBean("accessFilter");
    CharacterEncodingFilter cef = (CharacterEncodingFilter) rootContext.getBean("characterEncodingFilter");

    DelegatingFilterProxy dfp = new DelegatingFilterProxy("springSecurityFilterChain");

    EnumSet<DispatcherType> dts = EnumSet.allOf(DispatcherType.class);

    // Access log filter
    ctx.addFilter("accessFilter", af).addMappingForUrlPatterns(dts, true, "/*");
    // Error wrapper filter
    // Character encoding filter
    ctx.addFilter("characterEncodingFilter", cef).addMappingForUrlPatterns(dts, true, "/*");
    // Spring security filter
    ctx.addFilter("spring-security", dfp).addMappingForUrlPatterns(dts, true, "/*");

}

From source file:alfio.config.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);// ww w .ja  va  2 s .  c o  m

    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);

}