如何修改请求的url地址

可以有两种方法:

一种是采用dispatcher的forward方法,进行内部重定向到新的url地址上

另一种是继承HttpServletRequestWrapper,重写URL相关方法。

第一中方法可以参见如下网页:SpringBoot 利用过滤器Filter修改请求url地址

实现此方法后,发现有个巨大的坑,并且无法解决。。。

因为我们都采用的是spring boot框架,进行单元测试使用的是mockmvc,类似this.mvc.perform(post(...

这种形式,该mockMvc使用的dispatcher是org.springframework.mock.web.MockRequestDispatcher,和正常请求

时获取的dispatcher(采用tomcat):org.apache.catalina.core.ApplicationDispatcher是不同的,该Dispatcher不会处理forward

请求,直接返回mock的forward结果为空字符串,根本不会真正路由到forward的controller进行处理。

实力证明:Improve MockMvc to follow redirects and forwards [SPR-14342] Spring MockMvc redirect not working

上文的网站上说,如果要测试forward的url,自己去写单元测试请求forward以后的url地址,MockRequestDispatcher不支持

forword方法。

因此,为了单元测试可以正常执行,我们可以采用第二种方案。

该方面的模板代码如下:

    private HttpServletRequestWrapper rewriteUrl(HttpServletRequest hr) {
        return new HttpServletRequestWrapper(hr){

            @Override
            public String getRequestURI() {
                // TODO Auto-generated method stub
                String rewriteUrl;
                String requestURI=hr.getRequestURI();
                return (rewriteUrl = getRewriteUrl(requestURI)) == null ? requestURI : rewriteUrl;
               /*"/MiGuMgr/rs/service/com_sitech_acctmgr_inter_IPresentIssSvc3_cfm";*/
            }

            private String getRewriteUrl(String requestURI) {
                String rewriteUrl;
                if( (rewriteUrl = redirectUrlMap.get(requestURI)) != null){
                    return rewriteUrl;
                }
                return null;
            }

            @Override
            public StringBuffer getRequestURL() {
                // TODO Auto-generated method stub
               return new StringBuffer(getScheme() + "://" + getServerName() + ":" + getServerPort()  + getRequestURI());
//                return new StringBuffer("http://127.0.0.1:8080/MiGuMgr/rs/service/com_sitech_acctmgr_inter_IPresentIssSvc3_cfm");
            }

            @Override
            public String getServletPath() {
                // TODO Auto-generated method stub
//                hr.getServletContext()
                if(!StringUtils.isEmpty(getRewriteUrl(hr.getContextPath()+hr.getServletPath()))){
                    return getRewriteUrl(hr.getContextPath()+hr.getServletPath()).substring(hr.getContextPath().length());
                }
                    return hr.getServletPath();
            }
            
            
        };
    }

这样重新了request就咩有问题了。

你可能感兴趣的:(如何修改请求的url地址)