I'm using Spring, but this question applies to all JSP-controller type designs.
The JSP page references data (using tags) which is populated by the corresponding controller. My question is, where is the appropriate place to perform formatting, in JSP or the controller?
So far I've been preparing the data by formatting it in my 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);
}
}
The JSP file would look something like:
Name = <c:out value="${person. name}" /><br>
Birth Date = <c:out value="${person. birthDate}" /><br>
Location = <c:out value="${person. location}" /><br>
I know that JSP does have some provisions for formatting,
<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>
<fmt:formatDate type="date" value="${person. birthDate}" />
But this only works with Java's java.util.Format
. What if I need more complex or computed values. In such a case putting the code in the JSP would be cumbersome (and ugly).
I'm curious if this is following the spirit Spring/JSP/MVC. In other words, is the controller part of the view? Where is the preferred place to perform view related formatting? Should my controller just be returning the object (Person) instead of a Map of formatted values?