在Spring MVC中修改请求URI [英] Modify request URI in spring mvc
问题描述
我有一个基于Spring MVC的应用程序.我想在请求URI到达控制器之前对其进行修改.例如,控制器的RequestMapping为"abc/xyz",但即将到来的请求为"abc/1/xyz".我想修改传入的请求以将其映射到控制器.
I have a spring mvc based application. I want to modify the request URI before it reaches controller. For example, RequestMapping for controller is "abc/xyz" but the request coming is "abc/1/xyz". I want to modify incoming request to map it to controller.
解决方案1:实现拦截器并修改传入的请求URI.但是这里的问题是,因为没有控制器与URI模式"abc/1/xyz"匹配,所以它甚至都没有进入拦截器.(如果存在,我可能会丢失一些启用它的功能) 避开它可能是因为同时拥有URI和控制器的请求映射.
Solution1: Implement interceptor and modify incoming request URI. But the problem here is that as there is no controller matching the URI pattern "abc/1/xyz", it does not even goes to interceptor.(I might be missing something to enable it if its there) Get around for it could be to have both of URI as request mapping for controller.
还有哪些其他解决方案?是否有办法在春天之前处理这个请求.正如在web.xml的过滤器中处理它一样,我只是在弥补它.
What other solutions could be there? Is there a way to handle this request even before it comes to spring. As in handle it at filter in web.xml, i am just making it up.
推荐答案
您可以编写一个servlet Filter
,它包装HttpServletRequest
并为方法getRequestURI
返回不同的值.像这样的东西:
You could write a servlet Filter
which wraps the HttpServletRequest
and returns a different value for the method getRequestURI
. Something like that:
public class RequestURIOverriderServletFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
chain.doFilter(new HttpServletRequestWrapper((HttpServletRequest) request) {
@Override
public String getRequestURI() {
// return what you want
}
}, response);
}
// ...
}
必须将servlet过滤器配置添加到web.xml
.
The servlet filter configuration must be added into the web.xml
.
但是,诚挚的,也许还有其他方法可以解决您的问题,除非您有充分的理由,否则您不应该这样做.
But sincerly, there is probably other way to solve your problems and you should not do this unless you have very good reasons.
这篇关于在Spring MVC中修改请求URI的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!