gpt4 book ai didi

Spring MVC - 从所有拦截器中排除 Assets

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

我试图找出一种方法来避免必须从所有拦截器中排除静态内容,而不必指定 exclude-mapping应该忽略这些的每个拦截器的标记。我的 context.xml 的一部分如下:

<mvc:resources mapping="/assets/**" location="/assets/"/>

<mvc:interceptors>

<bean class="com.myapp.security.interceptor.SecurityInterceptor" />

<mvc:interceptor>
<mvc:mapping path="/**" />
<mvc:exclude-mapping path="/assets/**" />
<bean class="com.myapp.interceptor.MessageInterceptor" />
</mvc:interceptor>

</mvc:interceptors>

如您所见,我指定了 /assets/免于被排除在 MessageInterceptor 之外。但是,我也希望 SecurityInterceptor 也排除资源。在 DRY 之后,必须指定一个 exclude-mapping 似乎不合理。对于每个拦截器(因为不应该真的有理由拦截资源)。

我四处搜索,找不到任何解决方案。任何帮助表示赞赏!

谢谢

最佳答案

我正在努力想出任何方法来实现您想要的配置。也许其他人可以提供解决方案。

可以实现您想要的快速代码解决方案如下:

public abstract class ResourceExcludingHandlerInterceptor implements HandlerInterceptor
{

@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception
{
if (!isResourceHandler(handler))
{
doAfterCompletion(request, response, handler, ex);
}
}

public abstract void doAfterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception;

public abstract void doPostHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception;

public abstract boolean doPreHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception;

/**
* <p>
* Determine if the request is about to be handled by a mapping configured
* by <mvc:resources>
* </p>
*
* @param handler
* - the handler to inspect
* @return - true if this is a <mvc:resources> mapped request, false
* otherwise
*/
private boolean isResourceHandler(Object handler)
{
return handler instanceof ResourceHttpRequestHandler;
}

@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception
{
if (!isResourceHandler(handler))
{
doPostHandle(request, response, handler, modelAndView);
}
}

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
{
return isResourceHandler(handler) ? true : doPreHandle(request, response, handler);
}
}

然后你可以让你的 HandlerInterceptor 实现扩展这个抽象类。由于 基本上是注册 ResourceHttpRequestHandler 实例的一种简写方式,这将确保您的 HandlerInterceptor 实现简单地忽略映射为由一个处理的任何请求。

关于Spring MVC - 从所有拦截器中排除 Assets ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18404906/

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