how to get the base url from jsp request object?

前端 未结 6 920
予麋鹿
予麋鹿 2020-11-30 07:10

How to get the base url from the jsp request object? http://localhost:8080/SOMETHING/index.jsp, but I want the part till index.jsp, how is it possible in jsp?

6条回答
  •  遥遥无期
    2020-11-30 08:07

    So, you want the base URL? You can get it in a servlet as follows:

    String url = request.getRequestURL().toString();
    String baseURL = url.substring(0, url.length() - request.getRequestURI().length()) + request.getContextPath() + "/";
    // ...
    

    Or in a JSP, as , with little help of JSTL:

    <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
    
    ${req.requestURL}
    
    ...
    
        
    
    

    Note that this does not include the port number when it's already the default port number, such as 80. The java.net.URL doesn't take this into account.

    See also:

    • Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP

提交回复
热议问题