1. 程式人生 > >jsp中EL表示式不起作用的問題

jsp中EL表示式不起作用的問題

SpringMVC過程中出現異常,開發環境如下:
開發工具:IDEA
JDK:1.8.0_65
Spring Version:4.2.4
Servlet Version:3.1.0
Maven:3.3.0

問題:在jsp頁面中使用el表示式取值,取不到值,但是使用jsp中巢狀java程式碼可以取到值,對應程式碼如下:

// 後臺賦值:
String viewName = SUCCESS;
ModelAndView modelAndView = new ModelAndView(viewName);
// 新增模型資料到ModelAndView中
 modelAndView.addObject("time"
, new Date());
<!-- Jsp頁面取值-->
time: ${requestScope.time}
<br>
time: ${requestScope.get("time")}
<br>
time: <%=request.getAttribute("time")%>
<br><br>
time: ${time}

結果:

time: ${requestScope.time} 
time: ${requestScope.get("time")} 
time: Wed Dec 23 16:02:03 CST 2015 
time: ${time}

從結果來看,jsp中巢狀java程式碼可以取值成功,那麼後臺賦值成功,應該是前臺頁面通過el表示式取值失敗。

通過google,發現解決方法,在這裡記一下,以備後面需要。
解決方法:
在使用el表示式的jsp中配置:

<%@page isELIgnored="false" %>

該設定代表在本jsp中使用el表示式,可以解析其中的值。若isELIgnored設定為true,代表在本頁不使用el表示式,當做字串解析出來顯示。此時,el表示式正常工作,顯示正常。那麼為什麼會這樣?首先檢視,web.xml中配置的<web-app>標籤,jsp servlet版本是多少?發現之前配置如下:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.5//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
...
</web-app>

發現使用版本為2.3,google一下發現oracle官方如下描述:

If isELIgnored is true, EL expressions are ignored when they appear in static text or tag attributes. If it is false, EL expressions are evaluated by the container only if the attribute has rtexprvalue set to true or the expression is a deferred expression.

The default value of isELIgnored varies depending on the version of the web application deployment descriptor. The default mode for JSP pages delivered with a Servlet 2.4 descriptor is to evaluate EL expressions; this automatically provides the default that most applications want. The default mode for JSP pages delivered using a descriptor from Servlet 2.3 or before is to ignore EL expressions; this provides backward compatibility.

大意就是:
如果isELIgnored是true,當EL表示式出現在文字或者標籤屬性時被忽略。如果是false,則EL表示式通過容器來決定如何解析,只有屬性有返回表示式被設定為true或者表示式是一個延遲表示式時不解析。

isELIgnored的值取決於web應用部署描述符的版本。使用Servlet2.4的描述符的JSP頁面預設是解析EL表示式,即表示式有效。這預設提供了大部分應用想要的情況。而使用Servlet2.3或者更早的描述符的JSP頁面預設是忽略EL表示式的,即不解析EL表示式,這樣就提供了向後相容性。

也就是說,描述符2.4或者更新的版本,isELIgnored預設值為false,而2.3或者 更早的版本isELIgnored預設值為true。就導致了出現EL表示式無效的情況。
至此,問題已經解決。
網上還有一個解決方案,本人未測試:
在web.xml檔案中新增如下配置:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <el-ignored>false</el-ignored>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

目測應該好使,原理也是設定jsp的el表示式是否可用。