Modify request URI in spring mvc

試著忘記壹切 提交于 2019-12-10 23:46:55

问题


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.

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.

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.


回答1:


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

    // ...

 }

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.




回答2:


You can use a URL Re-Write which are specifically meant for this purpose i.e. transform one request URI to another URI based on some regex.



来源:https://stackoverflow.com/questions/17549093/modify-request-uri-in-spring-mvc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!