开发者

In a JSP scriptlet, how do you access a java.util.Date value passed from a Spring MVC ModelMap?

FooController.java:

@RequestMapping(value = "/foo", method = RequestMethod.GET)
public final String foo(HttpServletRequest request, Mod开发者_开发知识库elMap 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?


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 Spring


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"), not getParameter. 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.Dates based on patterns, <fmt:formatDate>.


That'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


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).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜