JSP 使用 ${pageContext.request.contextPath} 無效
阿新 • • 發佈:2021-12-09
${pageContext.request.contextPath}
通過 ${pageContext.request.contextPath} 可在 JSP 中取得當前的專案絕對路徑,比如當前專案是 http://localhost:8080/demo, 則 ${pageContext.request.contextPath} 代表的就是 /demo,其中 / 代表 http://localhost:8080,所以一般使用 ${pageContext.request.contextPath} 定位資源。
JSP 中 isELIgnored 屬性
isELIgnored 屬性表示是否忽略 EL 表示式,如果值為 true,那麼 JSP 中的 EL 表示式被當成字串處理。比如下面這個表示式 ${2000 / 20}, 在 isELIgnored="true" 時輸出為字串 ${2000 / 20},當 isELIgnored="false" 時輸出為 100。
問題原因
Maven 專案預設使用 web-app 2.3 版本(各版本 web-app 標籤),據說是為了擴充套件性,到了 web-app 2.5 才預設支援 EL 表示式,於是導致使用 ${pageContext.request.contextPath} 無效。
解決方案
1.JSP 中新增屬性 isELIgnored="false"
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" isELIgnored="false" %>
2.使用 web-app 4.0 版本
<?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">
</web-app>