You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring MVC中JSP使用EL表达式${message}不显示值的原因咨询

为什么Spring MVC中JSP的EL表达式${message}不生效?

问题场景

我在学习Spring MVC,用JSP做视图层时遇到了问题:

Controller代码:

@RequestMapping
public String sayHello(ModelMap model)
{
    model.addAttribute("message","welcome to 3-IDIOTS web store");
    return "hello";
}

对应的hello.jsp代码:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>Title</title>
</head>
<h2>${message}</h2>
<body>
</body>
</html>

启动Tomcat后,页面直接显示${message}而不是预期的文本。虽然用JSP脚本<%=message%>能正常获取值,但想知道EL表达式失效的原因。

原因分析

EL表达式直接显示而不解析,核心原因是JSP页面默认禁用了EL表达式,常见触发场景有两种:

  • JSP页面未明确开启EL支持:旧版本JSP规范中,isELIgnored属性默认值为true,会忽略所有EL表达式。
  • Web应用的Servlet版本过低:如果web.xml中配置的Servlet版本是2.3或更早,容器会默认禁用EL表达式。

解决方法

方法1:在JSP页面添加EL启用指令

在JSP顶部的page指令中加入isELIgnored="false",强制开启EL支持:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>

方法2:升级web.xml的Servlet版本

确保web.xml使用Servlet 2.4及以上版本的命名空间和配置,示例如下:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
         http://java.sun.com/xml/ns/javaee/web-app_2_4.xsd"
         version="2.4">
    <!-- 其他配置 -->
</web-app>

补充说明

你用<%=message%>能正常工作,是因为这是JSP脚本语法,它直接从request域中获取属性值,不受EL表达式开关的影响,属于旧版JSP的写法;而EL表达式是更简洁的域对象取值方式,需要明确开启才能生效。

内容的提问来源于stack exchange,提问作者Abdelrahman Essam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 04:45:30