The getContextPath() method of the HttpServletRequest interface in the Java Servlet API returns the context path of the web application. The context path is the prefix of the request URI that indicates the context under which the request was made.
Example 1:
Suppose we have a web application deployed on Tomcat with context path "/myapp" and a servlet which receives requests at "/myapp/servlet". We can retrieve the context path using the following code snippet:
In a JSP file, we can use the JSTL library to output the context path. The following code outputs the context path as part of a URL:
In this example, the c:url tag constructs a URL by appending the context path to the given value ("/css/style.css"). The resulting URL (e.g. "/myapp/css/style.css") is stored in the cssUrl variable and is used as the href attribute of a link tag.
Package library:
The getContextPath() method is part of the javax.servlet.http package, which is part of the Java Servlet API.
Java HttpServletRequest.getContextPath - 30 examples found. These are the top rated real world Java examples of HttpServletRequest.getContextPath extracted from open source projects. You can rate examples to help us improve the quality of examples.