在JSP scriptlet中,如何访问从Spring MVC ModelMap传递的java.util.Date值? [英] In a JSP scriptlet, how do you access a java.util.Date value passed from a Spring MVC ModelMap?

查看:55
本文介绍了在JSP scriptlet中,如何访问从Spring MVC ModelMap传递的java.util.Date值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FooController.java:

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"/>

为什么JSP脚本无法获取添加到FooControllerModelMapmyDate值?

Why does the JSP scriptlet fail to obtain the myDate value that was added to the ModelMap in the FooController?

推荐答案

ModelMap中的属性存储为请求(或会话,取决于您的声明)属性,而不是参数. 控制器方法完成执行后,Spring会转发到与返回的视图名称关联的JSP.

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.

因此,在您的JSP中,您必须使用request.getAttribute("myDate"),而不是getParameter. 实际上,您应该远离JSP中的Java代码,但您还应该了解EL表达式的作用-在您的情况下,${myDate}找到名为"myDate"的请求属性.

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 .: JSTL中已有一个标记,用于根据<fmt:formatDate>模式对java.util.Date进行格式化.

P.S.: There is an existing tag in JSTL for formatting java.util.Dates based on patterns, <fmt:formatDate>.

这篇关于在JSP scriptlet中,如何访问从Spring MVC ModelMap传递的java.util.Date值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆