在Java Web开发中,getContextPath() 是一个常用的方法,用于获取当前Web应用程序的上下文路径(Context Path)。Context Path 是Web应用程序部署时的根路径,用于唯一标识该应用程序在Web服务器上的位置。
getContextPath() 方法的使用
在Servlet或JSP页面中,可以通过以下方式获取Context Path:在Servlet中获取Context Path:
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class MyServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String contextPath = request.getContextPath();
response.getWriter().println("Context Path: " + contextPath);
}
}
在JSP页面中获取Context Path:
jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Context Path Example</title>
</head>
<body>
<h1>Context Path: <%= request.getContextPath() %></h1>
</body>
</html>