Reputation: 1571
I have a model like this defined...
public class Product{
private long timestamp;
// get/set follows...
}
The timestamp field is fine for the database, since I persist the data via JPA. However, in the JSP output, I don't want to present the timestamp as long, I want to present it as a customized String. I would like to define the long/String conversion in a custom method.
I could convert the timestamp field to DateTime or something, but this is a general question - how is it possible to process model data without modifying the model itself, because it's just for the view? I looked into Spring Conversion and Formatter SPIs, but that doesn't seem to fit here (Formatter is mainly for user input, Conversion applies to the whole model and I just want to manipulate one field of the model).
I already thought of creating a new object just for the view, passing all the data from the database model and manipulate it there, but there must be a better solution...
EDIT
Some additonal code...here is my 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;
And this is the JSP (simplified):
<c:forEach items="${products}" var="currentproduct">
<tr>
<td>${currentproduct.timestamp}</td>
<td>${currentproduct.name}</td>
</tr>
</c:forEach>
Upvotes: 1
Views: 3747
Reputation: 1804
Spring views normally use getters and setters to access the data of a model. The best solution would be to provide a getter that formats the date or convert the long
object to a Date
object or some other required format. From the views, you then access this getter method.
EDIT
public class Product{
private long timestamp;
public Date getDate() {
return new Date(timestamp);
}
}
and from the view
<c:forEach items="${products}" var="currentproduct">
<tr>
<td>${currentproduct.date}</td>
<td>${currentproduct.name}</td>
</tr>
</c:forEach>
Upvotes: 1
Reputation: 120791
What about adding a "special" getter that returns a formated string?
Or a JSP Tag that does the formatting like: jsp:
<td><my:formatLongTimestamIntoSomethingUsefull
value="${currentproduct.timestamp}"/></td>
Upvotes: 1