我有一个这样定义的模型...
public class Product{
private long timestamp;
// get/set follows...
}
时间戳字段对于数据库来说很好,因为我通过 JPA 保存数据。但是,在 JSP 输出中,我不想将时间戳显示得太长,我想将其显示为自定义字符串。我想在自定义方法中定义长/字符串转换。
我可以将时间戳字段转换为 DateTime 或其他内容,但这是一个普遍问题 - 如何在不修改模型本身的情况下处理模型数据,因为它只是用于 View ?我调查了Spring Conversion和 Formatter SPI,但这似乎不适合这里(Formatter 主要用于用户输入,Conversion 适用于整个模型,我只想操作模型的一个字段)。
我已经考虑过为 View 创建一个新对象,传递数据库模型中的所有数据并在那里对其进行操作,但必须有更好的解决方案......
编辑
一些附加代码...这是我的 Controller :
@RequestMapping(method=RequestMethod.GET, value="/")
public ModelAndView getAllProducts() {
List<Product> products = daoReader.findAllProducts();
ModelAndView mv = new ModelAndView("myproductview");
mv.addObject("products", products);
return mv;
这是 JSP(简化版):
<c:forEach items="${products}" var="currentproduct">
<tr>
<td>${currentproduct.timestamp}</td>
<td>${currentproduct.name}</td>
</tr>
</c:forEach>
最佳答案
Spring View 通常使用 getter 和 setter 来访问模型的数据。最好的解决方案是提供一个 getter 来格式化日期或将 long
对象转换为 Date
对象或其他一些所需的格式。然后,您可以从 View 中访问此 getter 方法。
编辑
public class Product{
private long timestamp;
public Date getDate() {
return new Date(timestamp);
}
}
从 View 来看
<c:forEach items="${products}" var="currentproduct">
<tr>
<td>${currentproduct.date}</td>
<td>${currentproduct.name}</td>
</tr>
</c:forEach>
关于java - 操作 JSP 输出的 Spring MVC 模型字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9301452/