Saturday, January 28, 2017

Model value ${} is not displayed in the JSP

The Spring Expression Language (SpEL) is a powerful expression language that supports querying and manipulating an object graph at runtime. It can be used with XML or annotation-based Spring configurations. Sometimes, it will make you to scratch your head, when things not working. Recently i encountered a wired problem while working on the Spring MVC project, me trying to set a value into a model, and display the value in JSP via EL, e.g ${name}, but it just outputs the result as it is – ${name}, not the “value” stored in the model.

Controller

 @Controller  
 public class HelloController {  
      @RequestMapping("/hello")  
      public String hello(Model model) {  
           model.addAttribute("name", "John Doe");  
           return "welcome";  
      }  
 }  

JSP File

 <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
 <!DOCTYPE html>  
 <html>  
 <head>  
      <title>Home Page</title>  
      <link rel='stylesheet' href='<c:url value="/resources/css/style.css" />' type='text/css' media='all' />   
 </head>  
 <body>  
      <h2>Hello World, Spring MVC</h2>  
      <p>Welcome, ${name}</p>  
      <p>Welcome, ${name}</p>  
      <p>Welcome, ${name}</p>  
 </body>  
 </html>  

Everything looks good in the above, then what makes the jsp page just to dump the EL script as it is. Actually the issue is caused by the old JSP 1.2 descriptor. If you are using the old JSP 1.2 descriptor, defined by DTD ,for example web.xml. The EL is disabled or ignored by default, you have to enable it manually, so that it will outputs the value store in the "name" model.

JSP 1.2 web.xml
 <!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>  
 </web-app>  

So you just add the following tag <%@ page isELIgnored="false" %> , this will resolve the issue.

JSP 2.0
If you are using the standard JSP 2.0 descriptor, defined by w3c schema ,for example web.xml. The EL is enabled by default, and you should see the value stored in the "name" model, which is "John Doe".

 <web-app id="WebApp_ID" version="2.4"  
      xmlns="http://java.sun.com/xml/ns/j2ee"  
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
      xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  
      http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
 //...  
 </web-app>  

Happy Programming...!!!

No comments:

Post a Comment