FooController.java:
@RequestMapping(value = "/foo", method = RequestMethod.GET)
public final String foo(HttpServletRequest request, ModelMap model)
{
java.util.Date myDate = new java.util.Date();
model.addAttribute("myDate", myDate);
return "foo";
}
foo.jsp:
<%
java.util.Date myUtilDate = (java.util.Date)request.getParameter("myDate");
org.joda.time.DateTime myJodaDate = new org.joda.time.DateTime(myUtilDate);
%>
<joda:format value="${myJodaDate}" style="LL"/>
Why does the JSP scriptlet fail to obtain the myDate
value that was added to the ModelMap
in the FooController
?
Answer by Nicolae Albu is right - this is request attribute, not parameter. Attribute is something you associate with request yourself, in code, using API (in this case - Spring MVC does that using Model). Parameters are added by Servlet Container, not you, and they represent URL/POST parameters sent by browser.
The only thing to add is that ${varName} is equivalent to pageContext.findAttribute("varName"); and request.getAttribute("varName") is equivalent to pageContext.getAttribute("varName", PageContext.REQUEST_SCOPE) (if you're not sure what this is about, look up documentation on page, request, session and application scopes in Servlets+JSPs).
The attributes in the ModelMap are stored as request (or session, depending on your declarations) attributes, not parameters. After your controller method finishes execution, Spring forwards to the JSP associated with the returned view name.
So, in your JSP, you must use
request.getAttribute("myDate")
, notgetParameter
. Actually, you should stay away from Java code in JSPs, but you should also understand what EL expressions do - in your case,${myDate}
finds the request attribute named "myDate".P.S.: There is an existing tag in JSTL for formatting
java.util.Date
s based on patterns,<fmt:formatDate>
.You should be able to just access your ModelMap parameter with
${myDate}
- see similar questions: How do I access ModelMap in a jsp? and JSPs not displaying objects from model in SpringThat's a request parameter, you need to bind appropriately coming off the wire, I wrote a blog post on this last week:
http://linkedjava.blogspot.com/2011/06/spring-controller-with-date-object.html