How to get full URL in JSP

跟風遠走 提交于 2019-12-06 06:27:17

问题


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


回答1:


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




回答2:


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.




回答3:


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

}


来源:https://stackoverflow.com/questions/27926854/how-to-get-full-url-in-jsp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!