如何在JSP中获取完整的URL

时间:2015-01-13 16:29:13

标签: java jsp url jsp-tags

我如何获得JSP页面的完整URL。

例如,网址可能是http://www.example.com/news.do/?language=nl&country=NL

如果我做以下事情,我总是得到news.jsp而不是.do

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

4 个答案:

答案 0 :(得分:4)

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

request.getQueryString();

它返回id1 = something& id2 = something& id3 = something

See This

答案 1 :(得分:3)

您需要致电request.getRequestURL()

  

重建客户端用于发出请求的URL。返回的URL包含协议,服务器名称,端口号和服务器路径,但不包括查询字符串参数。

答案 2 :(得分:0)

我找到了解决方案。这可能不是完美的解决方案。但这是可行的解决方案。

String qs = request.getQueryString();
String foo = request.getRequestURL().toString()+"?"+qs;

答案 3 :(得分:-1)

/**
* 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();

}

相关问题