【问题标题】:HttpServletResponse make url a forward slash(/) become two forward slash(//)HttpServletResponse 使 url 一个正斜杠(/)变成两个正斜杠(//)
【发布时间】:2017-05-04 09:13:13
【问题描述】:

html中的url:

<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">

控制器:

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 {

    }

}

response.sendRedirect() 的 targetUrl 是:

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

问题是何时重定向: chrome浏览器中的url变成:

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

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

【问题讨论】:

    标签: java http spring-mvc servlets


    【解决方案1】:

    我自己解决了这个问题;抱歉遗漏了信息,该项目有一个过滤器来处理防御 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;
    }
    ..
    }
    

    所以字符串 "to=https://sale.xxx.com/act/UuzWBLwPKX.html", 在 Java 中:“https://sale.xxx.com/act/UuzWBLwPKX.html” 所以解决方案是:

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

    【讨论】:

    • bug 我还是不知道为什么会变成“//act”
    【解决方案2】:

    使用URI Class 解决此问题

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

    结果:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 1970-01-01
      • 2021-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-05-17
      • 2015-08-11
      • 2023-03-16
      相关资源
      最近更新 更多