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表达式,这样就提供了向后兼容性。

Oracle文档:https://docs.oracle.com/cd/E19316-01/819-3669/bnaic/index.html

也就是说,描述符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表达式是否可用。

  • 59
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 13
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 13
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值