在Spring MVC开发中, 开发人员可能会设置某个值到 model 中, 并通过EL表达式在JSP显示, 例如: ${msg}, 但并没有解析为对应的 “value”, 输出结果还是老样子: ${msg}。也就是说JSP中 的 EL 不起作用了,为什么呢?
SpringMVC的Controller代码如下:
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.AbstractController; public class ABCController extends AbstractController { @Override protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception { ModelAndView model = new ModelAndView("HelloWorldPage"); model.addObject("msg", "hello world"); return model; } }
JSP 页面的内容如下:
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %> <html> <body> ${msg} </body> </html>
在 Spring MVC 的入门项目中, 这是最常见的问题。实际上这是因为使用了 JSP 1.2 规范引起的。
如果您使用了老旧的JSP 1.2描述方式, 即使用了 DTD 定义:
web.xml
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "https://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> //... </web-app>
这种情况下, EL表达式默认是禁用或者忽略的, 必须手动启用,才会输出 model 中的值。示例如下:
<%@ taglib prefix="c" uri="https://java.sun.com/jsp/jstl/core" %> <html> <head> <%@ page isELIgnored="false" %> </head> <body> ${msg} </body> </html>
可以看到,其中使用了 <%@ page isELIgnored="false" %> 来开启 EL 表达式。
如果使用了 标准的 JSP 2.0 描述符, 即通过w3c schema来定义, 示例如下:
web.xml
<web-app id="WebApp_ID" version="2.4" xmlns="https://java.sun.com/xml/ns/j2ee" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://java.sun.com/xml/ns/j2ee https://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"> //... </web-app>
或者是更新的 Servlet 3.1 规范(也没有 DTD 定义):
web.xml
<web-app xmlns="https://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="https://xmlns.jcp.org/xml/ns/javaee https://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> //... </web-app>
则EL是默认启用的, 可以通过EL解析到存储在model中 “msg”的值 ,即“hello world”。
参考资料:
https://blog.csdn.net/renfufei/article/details/54599835
https://www.mkyong.com/spring-mvc/modelandviews-model-value-is-not-displayed-in-jsp-via-el