The context path always comes first in a request URI. The path starts with a “/” character but does not end with a “/” character. When I have a web application with the URL like http://localhost:8080/myapp` then
/myapp` is the context path.
For servlets in the default (root) context, this method returns ""
(empty string).
package org.kodejava.servlet;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.ServletException;
import java.io.IOException;
import java.io.PrintWriter;
@WebServlet(urlPatterns = "/context-path")
public class ContextPathDemo extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// HttpServletRequest.getContextPath() returns the portion
// of the request URI that indicates the context of the
// request.
String contextPath = req.getContextPath();
PrintWriter pw = res.getWriter();
pw.print("Context Path: " + contextPath);
}
}
You’ll get the following information in your browser:
Context Path: /webapp
Maven dependencies
<!--https://search.maven.org/remotecontent?filepath=javax/servlet/javax.servlet-api/4.0.1/javax.servlet-api-4.0.1.jar-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
Latest posts by Wayan (see all)
- How do I build simple search page using ZK and Spring Boot? - March 8, 2023
- How do I calculate days between two dates excluding weekends and holidays? - January 12, 2023
- How do I discover the quarter of a given date? - January 11, 2023