获取当前工程名

Java 端

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
	// 获取当前工程名,返回 /工程名
	String projectName = req.getContextPath();
	System.out.println(projectName);
}

Web 端

JSP 语法

<% out.println(request.getContextPath()); %><br>
<%=request.getContextPath() %><br>

  JSP 的另一个内置对象是 pageContext 对象可以用 getRequest() 方法获取 request 对象,于是我就想试试用 pageContext.getRequest().getContextPath() 这个方法来获取工程名,但是尝试之后,发现报错了,错误提示是在 ServletRequest 类中没有 getContextPath() 这个方法。
  原因就是 pageContext.getRequest() 返回的 ServletRequest 类型的对象,而 getContextPath() 方法是在 HttpServletRequest 类中定义的,因此找不到 getContextPath() 方法。
  再提一下,pageContext.getRequest().equals(request) 返回的是 true,因为 pageContext.getRequest()获取的 ServletRequest 其实就是 request 这个HttpServletRequest 对象向上转型得来的,所以他们虽然是不同的类型,但是是相同的对象,故调用 equals() 方法返回的结果是 true。

EL 表达式

${pageContext.request.contextPath}<br>

猜你喜欢

转载自blog.csdn.net/qq_40395874/article/details/114466350