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

时间秒杀一切 提交于 2019-12-12 04:28:42

问题


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?


回答1:


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




回答2:


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




回答3:


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




回答4:


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



来源:https://stackoverflow.com/questions/6399666/in-a-jsp-scriptlet-how-do-you-access-a-java-util-date-value-passed-from-a-sprin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!