問題是這樣:在搭建springMVC環境的時候,筆者寫了一個簡單的Controller如下:
@Controller public class HelloController { @RequestMapping(value = "/hello.do", method = RequestMethod.GET) public String hello(Model model) { model.addAttribute("hello", "hello_SpringMVC"); model.addAttribute("message", "Hello SpringMVC"); return "hello"; } }
調用這個控制器,返回hello.jsp,頁面代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${hello}<br> ${message}<br> ${hello123 } </body> </html>
正常情況下頁面應該會輸出字符串信息,可是實際上輸出結果是未經解析的EL表達式。
筆者查看了日志,發現hello和message都正確的轉發到了hello.jsp中,可是EL表達式為什么沒有正確的解析呢?
經過查閱資料,有四種情況下EL表達式是無法正確別解析的,
分別是:
- Application server in question doesn't support JSP 2.0. (應用服務器不支持JSP2.0)
- The
web.xml
is not declared as Servlet 2.4 or higher. (web.xml中servlet版本沒有聲明在2.4以上) - The
@page
is configured withisELIgnored=true
. (頁面上配置了<%@ page isELIgnored="true" %> ) - The web.xml is configured with
<el-ignored>true</el-ignored>
in<jsp-config>
. (web.xml中顯式地配置了忽略EL表達式)
最終發現我的web.xml中聲明的servlet版本是2.3,所以默認是不自動解析EL表達式的。
而我的web.xml這樣是使用了maven-archetype-webapp創建的緣故。
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> </web-app>
只要更改成如下即可, 版本最好是你項目中使用的JSP版本,
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> ... </web-app>
總結一下:頁面無法解析EL表達式是因為web.xml中JSP版本在2.4一下,而我在項目中使用的是JSP3.0,原因在於工程是通過maven-archetype-webapp創建的,而這個maven工程默認還在使用JDK1.5。