HttpServletResponse使url成为正斜杠(/)成为两个正斜杠(//)

时间:2017-05-04 09:13:14

标签: java http spring-mvc servlets

html中的网址:

<a href=""////jrdc.xxx.com/dh/nc?camp=19&mid=19&mat=121&unit=-&uuid=386931bea19dbba0e8f8c3291743d004a71669b5807d3eb49e150e08fcd93c83&aid=12&day=1493864666856&to=https://sale.xxx.com/act/UuzWBLwPKX.html" target="_blank">

contronller:

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public void clickLog(HttpServletRequest request, HttpServletResponse response) {
    try {
        // 
        String targetUrl = request.getParameter("to");         
       if(targetUrl != null && !targetUrl.contains("http")){
           targetUrl = "http://" + targetUrl;
       }
       response.sendRedirect(targetUrl);
    }catch (Exception e){

    }finally {

    }

}

targetUrl到response.sendRedirect()是:

https://sale.jd.com/act/UuzWBLwPKX.html

问题是重定向时: Chrome浏览器中的网址变为:

https://sale.xxx.com//act//UuzWBLwPKX.html

其中“/”之前的“/”变成“//”,我不想要这个结果,为什么会变成这个以及如何成为https://sale.xxx.com/act/UuzWBLwPKX.html

2 个答案:

答案 0 :(得分:0)

我自己解决了这个问题;抱歉遗漏信息,该项目有一个过滤器来处理防御XSS攻击的请求

public class FHttpServletRequest extends HttpServletRequestWrapper{

     public FHttpServletRequest(HttpServletRequest request) {
            super(request);
        }
     @Override
     public String getParameter(String name) {
        return escapeXss(super.getParameter(escapeXss(name)));
     }
    protected String escapeXss(String param) {
        if (StringUtils.isNotBlank(param)) {
           return 
     StringEscapeUtils.escapeHtml(StringEscapeUtils.escapeJavaScript(param));
    }
    return param;
}
..
}

所以String&#34; to = https://sale.xxx.com/act/UuzWBLwPKX.html&#34;, 在Java中:&#34; https://sale.xxx.com/act/UuzWBLwPKX.html" 所以解决方案是:

 String targetUrl = request.getParameter("to");
 targetUrl = StringEscapeUtils.unescapeJava(targetUrl);
if(targetUrl != null && !targetUrl.contains("http")){
....
}

答案 1 :(得分:-1)

使用URI Class解决此问题

URI uri = new URI(targetUrl).normalize();
System.out.println("Target URL ----> "+uri.toString());

结果:

Target URL ----> https://sale.xxx.com/act/UuzWBLwPKX.html