gpt4 book ai didi

spring - 如何在Spring中使用WebMvcConfigurerAdapter添加过滤器?

转载 作者:行者123 更新时间:2023-12-02 08:42:58 28 4
gpt4 key购买 nike

使用 WebApplicationInitializer,我可以轻松地在 onStartup() 方法中向 ServletContext 添加过滤器。

如何使用WebMvcConfigurerAdapter添加过滤器?我必须使用 XML 吗?

添加1

为了帮助大家更容易理解Spring Web Configuration,我画了下面的图。

现在您只需要先了解 Spring Web 配置背后的理性即可。然后从下面选择要继承的配置类以及要重写的方法。

查找它比记住这么多事情要轻松得多。

enter image description here

还有一篇关于 Spring Web 初始化的好文章:

http://www.kubrynski.com/2014/01/understanding-spring-web-initialization.html

添加2

根据Tunaki的回复,我检查了AbstractDispatcherServletInitializer。过滤器注册发生在以下代码中:

enter image description here

即使我重写了绿色的 getServletFilters() 方法,我仍然无法访问 registerServletFilter()Dyanmic 结果。那么如何通过addMappingForUrlPatterns()来配置过滤器呢?

看来我必须重写整个registerDispatcherServlet()方法。

最佳答案

WebMvcConfigurer 是一个接口(interface),用于为通过 @EnableWebMvc 启用的 Spring MVC 自定义基于 Java 的配置。 WebMvcConfigurerAdapter 只是一个为此接口(interface)提供默认空方法的适配器。

它不会配置使用过滤器的DispatcherServlet。因此,您无法使用 WebMvcConfigurer 来配置 servlet 过滤器。

要轻松配置过滤器,您可以继承 AbstractDispatcherServletInitializer并覆盖getServletFilters() :

public class MyWebAppInitializer extends AbstractDispatcherServletInitializer {

@Override
protected Filter[] getServletFilters() {
return new Filter[] { new CharacterEncodingFilter() };
}

}

如果您想进一步配置过滤器,则必须覆盖 onStartup相反:

@Override
public void onStartup(ServletContext servletContext) throws ServletException {
super.onStartup(servletContext);
servletContext.addFilter("name", CharacterEncodingFilter.class)
.addMappingForUrlPatterns(null, false, "/*");
}

关于spring - 如何在Spring中使用WebMvcConfigurerAdapter添加过滤器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33463918/

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