How to get full URL in JSP

2020-07-19 21:11发布

How would I get the full URL of a JSP page.

For example the URL might be http://www.example.com/news.do/?language=nl&country=NL

If I do things like the following I always get news.jsp and not .do

out.print(request.getServletPath()); out.print(request.getRequestURI()); out.print(request.getRequest()); out.print(request.getContextPath());

3条回答
一纸荒年 Trace。
2楼-- · 2020-07-19 21:38

/**
* Creates a server URL in the following format:
*
* <p><code>scheme://serverName:serverPort/contextPath/resourcePath</code></p>
*
* <p>
* If the scheme is 'http' and the server port is the standard for HTTP, which is port 80,
* the port will not be included in the resulting URL. If the scheme is 'https' and the server
* port is the standard for HTTPS, which is 443, the port will not be included in the resulting
* URL. If the port is non-standard for the scheme, the port will be included in the resulting URL.
* </p>
*
* @param request - a javax.servlet.http.HttpServletRequest from which the scheme, server name, port, and context path are derived.
* @param resourcePath - path to append to the end of server URL after scheme://serverName:serverPort/contextPath.
* If the path to append does not start with a forward slash, the method will add one to make the resulting URL proper.
*
* @return the generated URL string
* @author Cody Burleson (cody at base22 dot com), Base22, LLC.
*
*/
protected static String createURL(HttpServletRequest request, String resourcePath) {

	int port = request.getServerPort();
	StringBuilder result = new StringBuilder();
	result.append(request.getScheme())
	        .append("://")
	        .append(request.getServerName());

	if ( (request.getScheme().equals("http") && port != 80) || (request.getScheme().equals("https") && port != 443) ) {
		result.append(':')
			.append(port);
	}

	result.append(request.getContextPath());

	if(resourcePath != null && resourcePath.length() > 0) {
		if( ! resourcePath.startsWith("/")) {
			result.append("/");
		}
		result.append(resourcePath);
	}

	return result.toString();

}

查看更多
地球回转人心会变
3楼-- · 2020-07-19 21:55

You need to call request.getRequestURL():

Reconstructs the URL the client used to make the request. The returned URL contains a protocol, server name, port number, and server path, but it does not include query string parameters.

查看更多
地球回转人心会变
4楼-- · 2020-07-19 21:59

Given URL = http:/localhost:8080/sample/url.jsp?id1=something&id2=something&id3=something

request.getQueryString();

it returns id1=something&id2=something&id3=something

See This

查看更多
登录 后发表回答