本示例说明如何使用JSP的表达语言(EL)功能在JSP中获取Web应用程序上下文路径。要获取上下文路径,我们可以利用,它是每个JSP页面上都可用的隐式对象。从该对象可以访问各种对象,例如:pageContext
servletContext
session
request
response
要获取上下文路径值,您需要从request.contextPath对象中读取它。这contextPath对于构造诸如CSS,JavaScript和图像之类的Web资源的路径很有用。您需要在JSP页面中启用JSP表达式语言(EL)的一些库,这些库通常已经包含在Servlet容器中,例如Apache Tomcat,包括:
javax.servlet-api-3.0.1
javax.servlet.jsp-api-2.3.1
javax.servlet.jsp.jstl-api-1.2.1
首先让我们创建index.jsp文件。
<%@ page contentType="text/html;charset=UTF-8" %> <!DOCTYPE html> <html> <head> <title>JSP - Context Path</title> </head> <body> Web Application Context Path = ${pageContext.request.contextPath} </body> </html>
这是您的web.xml配置文件:
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> <!-- Config here. --> </web-app>