Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get the base url from jsp request object?

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?

like image 779
Maverick Avatar asked Jun 07 '11 20:06

Maverick


People also ask

What is the use of Request object in JSP?

Each time a client requests a page, the JSP engine creates a new object to represent that request. The request object provides methods to get HTTP header information including form data, cookies, HTTP methods, etc.

What is a JSP request?

The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the web container. It can be used to get request information such as parameter, header information, remote address, server name, server port, content type, character encoding etc.


1 Answers

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 <base>, 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" %> <c:set var="req" value="${pageContext.request}" /> <c:set var="url">${req.requestURL}</c:set> <c:set var="uri" value="${req.requestURI}" /> ... <head>     <base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" /> </head> 

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
like image 62
BalusC Avatar answered Sep 29 '22 20:09

BalusC