Get request URL in JSP which is forwarded by Servlet

后端 未结 8 1498
忘掉有多难
忘掉有多难 2020-11-29 22:27

How can I get request URL in JSP which is forwarded by Servlet?

If I run following code in JSP,

System.out.println(\"servlet path= \" + request.getSe         


        
8条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 22:56

    Try this instead:

    String scheme = req.getScheme();             
    String serverName = req.getServerName(); 
    int serverPort = req.getServerPort();    
    String uri = (String) req.getAttribute("javax.servlet.forward.request_uri");
    String prmstr = (String) req.getAttribute("javax.servlet.forward.query_string");
    String url = scheme + "://" +serverName + ":" + serverPort + uri + "?" + prmstr;
    

    Note: You can't get HREF anchor from your url. Example, if you have url "toc.html#top" then you can get only "toc.html"

    Note: req.getAttribute("javax.servlet.forward.request_uri") work only in JSP. if you run this in controller before JSP then result is null

    You can use code for both variant:

    public static String getCurrentUrl(HttpServletRequest req) {
        String url = getCurrentUrlWithoutParams(req);
        String prmstr = getCurrentUrlParams(req);
        url += "?" + prmstr;
        return url;
    }
    
    public static String getCurrentUrlParams(HttpServletRequest request) {
        return StringUtil.safeString(request.getQueryString());
    }
    
    public static String getCurrentUrlWithoutParams(HttpServletRequest request) {
        String uri = (String) request.getAttribute("javax.servlet.forward.request_uri");
        if (uri == null) {
            return request.getRequestURL().toString();
        }
        String scheme = request.getScheme();
        String serverName = request.getServerName();
        int serverPort = request.getServerPort();
        String url = scheme + "://" + serverName + ":" + serverPort + uri;
        return url;
    }
    

提交回复
热议问题