gpt4 book ai didi

java - 如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern?

转载 作者:行者123 更新时间:2023-12-01 21:49:23 24 4
gpt4 key购买 nike

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

<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 类看起来像这样

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

但正如您所看到的,过滤器应用于所有资源,而我只想为 /sampleUrl 映射过滤器。我们如何做到这一点?

最佳答案

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

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

关于java - 如何在 WebApplicationInitializer 中为 Servlet 过滤器指定 url-pattern?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35434978/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com