Modify request URI in spring mvc

2019-07-19 17:38发布

问题:

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.