gpt4 book ai didi

java - Spring WebFilter 映射

转载 作者:行者123 更新时间:2023-11-30 02:51:39 26 4
gpt4 key购买 nike

我正在尝试在我的 Spring 应用程序中添加 WebFilter。但是,我没有使用 .xml 文件(甚至没有 web.xml,因为我的应用程序不需要它)。

因此,我添加到扩展 AbstractAnnotationConfigDispatcherServletInitializer 的类中:

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

还有,我的RequestFilter.java:

@WebFilter("/test/*")
public class RequestFilter implements Filter {

@Override
public void init(FilterConfig filterConfig) throws ServletException { }

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException { }

@Override
public void destroy() { }

我期望仅过滤与 /test/* 模式匹配的请求,但对任何资源的请求都会被过滤。

如何映射我的过滤器?

谢谢。

最佳答案

@WebFilter - 不是 Spring 注释。 Spring 忽略它。方法 getServletFilters 返回过滤器数组,而不将它们映射到 URL。所以他们会触发每个请求。如果您不想在 web.xml 中编写 url 映射,可以使用 HandlerInterceptor而不是过滤器。它们可以在 DispatcherServletInitializer 中以编程方式映射:

public class SomeInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
// ...
return true;
}
}

@Configuration
@ComponentScan("com.example")
@EnableWebMvc
public class AppConfig extends WebMvcConfigurerAdapter {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry
.addInterceptor(new SomeInterceptor())
.addPathPatterns("/test/*");
}
}

public class WebAppInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(AppConfig.class);
ctx.setServletContext(servletContext);
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(ctx));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}

或者您可以定义自己的 WebFilter 注释!

首先,您需要实用程序类来匹配 URL 模式:

public class GlobMatcher {
public static boolean match(String pattern, String text) {
String rest = null;
int pos = pattern.indexOf('*');
if (pos != -1) {
rest = pattern.substring(pos + 1);
pattern = pattern.substring(0, pos);
}

if (pattern.length() > text.length())
return false;

for (int i = 0; i < pattern.length(); i++)
if (pattern.charAt(i) != '?'
&& !pattern.substring(i, i + 1).equalsIgnoreCase(text.substring(i, i + 1)))
return false;

if (rest == null) {
return pattern.length() == text.length();
} else {
for (int i = pattern.length(); i <= text.length(); i++) {
if (match(rest, text.substring(i)))
return true;
}
return false;
}
}
}

注释本身:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface WebFilter {
String[] urlPatterns();
}

URL 模式匹配的传递功能:

@Aspect
public class WebFilterMatcher {
@Pointcut("within(@com.example.WebFilter *)")
public void beanAnnotatedWithWebFilter() {}

@Pointcut("execution(boolean com.example..preHandle(..))")
public void preHandleMethod() {}

@Pointcut("preHandleMethod() && beanAnnotatedWithWebFilter()")
public void preHandleMethodInsideAClassMarkedWithWebFilter() {}

@Around("preHandleMethodInsideAClassMarkedWithWebFilter()")
public Object beforeFilter(ProceedingJoinPoint joinPoint) throws Throwable {
Object[] args = joinPoint.getArgs();
if(args.length > 0) {
HttpServletRequest request = (HttpServletRequest) args[0];
Class target = joinPoint.getTarget().getClass();
if (target.isAnnotationPresent(WebFilter.class)) {
String[] patterns = ((WebFilter) target.getAnnotation(WebFilter.class)).urlPatterns();
for (String pattern : patterns) {
if (GlobMatcher.match(pattern, request.getRequestURI())) {
return joinPoint.proceed();
}
}
}
}
return true;
}
}

拦截器:

@WebFilter(urlPatterns = {"/test/*"})
public class SomeInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
// ...
return true;
}
}

上下文配置有一点变化:

<beans> <!-- Namespaces are omitted for brevity -->
<aop:aspectj-autoproxy />

<bean id="webFilterMatcher" class="com.example.WebFilterMatcher" />

<mvc:interceptors>
<bean class="com.example.SomeInterceptor" />
</mvc:interceptors>
</beans>

关于java - Spring WebFilter 映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38465566/

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