我正在使用 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);
}
}
JSP 文件看起来像:
Name = <c:out value="${person. name}" /><br>
Birth Date = <c:out value="${person. birthDate}" /><br>
Location = <c:out value="${person. location}" /><br>
我知道 JSP 确实有一些格式化的规定,
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<fmt:formatDate type="date" value="${person. birthDate}" />
但这仅适用于 Java 的java.util.Format
. 如果我需要更复杂或计算的值怎么办。在这种情况下,将代码放在 JSP 中会很麻烦(而且很难看)。
我很好奇这是否遵循 Spring/JSP/MVC 的精神。换句话说,控制器是视图的一部分吗?执行视图相关格式化的首选位置在哪里?我的控制器是否应该只返回对象(Person)而不是格式化值的 Map?