This article Reprinted from (http://qify.iteye.com/blog/552386)
<% = Request. getcontextpath () %> returns the root path of the site to solve the relative path problem.
But it does not need to be used. For example, <a href = "<% = request. getcontextpath () %>/catalog. JSP ">, you can directly use <a href =" catalog. JSP "> OK. The two files are in the same directory. For example, if you want to generate a file and put it in a directory on the server, you can use request. getcontextpath () +/DIR to form a complete directory structure!
However, in JSP files, sometimes the path obtained through request. getcontextpath () is empty. Why?
The path attribute is not configured in context, so your project file is under the root directory, which is equivalent to Path = "";
That is, if you enter your server IP address in your browser, your JSP page is displayed, instead of the default Tomcat page. the string obtained by getcontextpath () is empty; it obtains the virtual directory;
If you want to obtain the actual physical path of the project file, you can use: <% = request. getrealpath ("/") %> to output: D:/web. Refer to the servlet interface:
Request. getscheme ();
The name of the returned protocol. The default value is HTTP.
Request. getservername ()
The host name displayed in your browser is returned. You can give it a try.
Getserverport ()
Get server port number
Request. getcontextpath () should be the name of the project. If the project is the root directory, an "", that is, an empty string. If the project is ABC, <% = request. getcontextpath () %> to get ABC, and the server path is automatically added. <a href = "XXXX. JSP "> refers to the XXX in the current path. for JSP pages, you can also set HTML: Base in the head to solve the path problem, but the most commonly used is request. getcontextpath.
Get the value of request. getcontextpath () in the JS file, and do not want to write too much JavaScript code in JSP:
One method is to use hidden:
<Input type = hidden name = contextpath value = <% = request. getcontextpath ()>
In the Js of this page, you can use scriptlet to assign values:
VaR A = '<% = request. getcontextpath ()>'
Or you can assign a value to a hidden control, and then retrieve it from JS, so that JS does not need to be written in JSP.
In practical applications, it is generally used to solve the problem of different paths in JSP testing and production environments:
<%
String appcontext = request. getcontextpath ();
String basepath = request. getscheme () + ": //" + request. getservername () + ":" + request. getserverport () + appcontext;
%>