gpt4 book ai didi

java - 在Spring/JSP中,应该在哪里进行格式化?

转载 作者:搜寻专家 更新时间:2023-10-31 19:51:22 25 4
gpt4 key购买 nike

我正在使用 Spring,但这个问题适用于所有 JSP Controller 类型的设计。

JSP 页面引用由相应 Controller 填充的数据(使用标签)。我的问题是,在 JSP 或 Controller 中执行格式化的合适位置在哪里?

到目前为止,我一直在通过在 Controller 中格式化数据来准备数据。

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 的精神。换句话说, Controller 是 View 的一部分吗?执行 View 相关格式化的首选位置在哪里?我的 Controller 应该只返回对象(人)而不是格式化值的映射吗?

最佳答案

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

  • 控制者
  • 标签库

我想说的是,在大多数情况下,标签库可能就是您想要的,因为 View 通常是关心格式化等事情的代码。

如果标准标签库无法帮助您实现目标,创建它们并不难,因此您可以自己制作。

关于java - 在Spring/JSP中,应该在哪里进行格式化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/361529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com