如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern? [英] How to specify url-pattern for Servlet filters in WebApplicationInitializer?

查看:95
本文介绍了如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Spring-web 的 WebApplicationInitializerweb.xml 文件转换为基于 Java 的配置.以下是定义的示例过滤器

I am converting a web.xml file to Java based configuration using Spring-web's WebApplicationInitializer. Following is the sample filter defined

<filter>
        <filter-name>sampleFilter</filter-name>
        <filter-class>com.SampleFilter</filter-class>
</filter>
<filter-mapping>
        <filter-name>sampleFilter</filter-name>
        <url-pattern>/sampleUrl</url-pattern>
</filter-mapping>

现在 WebApplicationInitializer 类看起来像这样

and now the WebApplicationInitializer class looks like this

class MyWebAppInitializer extends AbstractAnnotationConfigDispatcherServletInitializer{
   @Override
  protected Filter[] getServletFilters() {
    return new Filter[]{new SampleFilter()};
  }
  //other methods
} 

但是如您所见,过滤器应用于所有资源,而我只想为 /sampleUrl 映射过滤器.我们该怎么做?

But as you can see, the Filter is applied to all the resources, whereas I want to map the Filter just for /sampleUrl. How do we do that?

推荐答案

下面是我在我的一个项目中使用的完整示例:

Below a full example i used in one of my project :

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
    AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();

    //add MVC dispatcher servlet and map it to /
    ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher", new DispatcherServlet(rootContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
    dispatcher.setAsyncSupported(true);

    //add spring characterEncoding filter
    //to always have encoding on all requests
    EnumSet<DispatcherType> dispatcherTypes = EnumSet.of(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.ERROR);

    CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
    characterEncodingFilter.setEncoding("UTF-8");
    characterEncodingFilter.setForceEncoding(true);

    FilterRegistration.Dynamic characterEncoding = servletContext.addFilter("characterEncoding", characterEncodingFilter);
    characterEncoding.addMappingForUrlPatterns(dispatcherTypes, true, "/*");
    characterEncoding.setAsyncSupported(true);

    // specifies that the parser produced by this factory will
    // validate documents as they are parsed.
    SAXParserFactory.newInstance().setValidating(false);

    // add spring contextloader listener
    servletContext.addListener(new ContextLoaderListener(rootContext));
}

这篇关于如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆