In a JSP scriptlet, how do you access a java.util.

2019-09-15 19: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?

4条回答
叼着烟拽天下
2楼-- · 2019-09-15 19:56

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

查看更多
对你真心纯属浪费
3楼-- · 2019-09-15 19:58

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

查看更多
女痞
4楼-- · 2019-09-15 20:01

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

查看更多
Animai°情兽
5楼-- · 2019-09-15 20:11

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

查看更多
登录 后发表回答