在Spring/JSP中,应该在哪里执行格式化?

Ste*_*Kuo 5 java spring jsp jstl jsp-tags

我正在使用Spring,但这个问题适用于所有JSP控制器类型的设计.

JSP页面引用由相应控制器填充的数据(使用标记).我的问题是,在JSP或控制器中执行格式化的适当位置在哪里?

到目前为止,我一直在通过在控制器中格式化数据来准备数据.

public class ViewPersonController extends org.springframework.web.servlet.mvc.AbstractController
{
    private static final Format MY_DATE_FORMAT = new SimpleDateFormat(...);
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)
    {
        Person person = get person from backing service layer or database
        Map properties = new HashMap();

        // No formatting required, name is a String
        properties.put("name", person.getName());

        // getBirthDate() returns Date and is formatted by a Format
        properties.put("birthDate", MY_DATE_FORMAT.format(person.getBirthDate()));

        // latitude and longitude are separate fields in Person, but in the UI it's one field
        properties.put("location", person.getLatitude() + ", " + person.getLongitude());

        return new ModelAndView("viewPerson", "person", properties);
    }
}
Run Code Online (Sandbox Code Playgroud)

JSP文件看起来像:

Name = <c:out value="${person. name}" /><br>
Birth Date = <c:out value="${person. birthDate}" /><br>
Location = <c:out value="${person. location}" /><br>
Run Code Online (Sandbox Code Playgroud)

我知道JSP确实有一些格式化的规定,

<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<fmt:formatDate type="date" value="${person. birthDate}" />
Run Code Online (Sandbox Code Playgroud)

但这只适用于Java java.util.Format.如果我需要更复杂或计算的值,该怎么办?在这种情况下,将代码放入JSP中会很麻烦(而且很丑陋).

我很好奇这是否遵循精神Spring/JSP/MVC.换句话说,控制器是视图的一部分吗?执行视图相关格式的首选位置在哪里?我的控制器应该返回对象(Person)而不是格式化值的Map吗?

dav*_*000 5

JSP通常没有很多(或任何?)代码,所以你的选择就是

  • 调节器
  • 标签库

我会说在大多数情况下,标签库可能就是你想要的,因为通常视图是关注格式化等事情的代码.

如果标准标记库没有帮助您,那么它们就不难创建,因此您可以自行创建.