Note that there are some explanatory texts on larger screens.

plurals
  1. POIn Spring/JSP, where should formatting be performed?
    text
    copied!<p>I'm using Spring, but this question applies to all JSP-controller type designs.</p> <p>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?</p> <p>So far I've been preparing the data by formatting it in my controller.</p> <pre><code>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); } } </code></pre> <p>The JSP file would look something like:</p> <pre><code>Name = &lt;c:out value="${person. name}" /&gt;&lt;br&gt; Birth Date = &lt;c:out value="${person. birthDate}" /&gt;&lt;br&gt; Location = &lt;c:out value="${person. location}" /&gt;&lt;br&gt; </code></pre> <p>I know that JSP does have some provisions for formatting,</p> <pre><code>&lt;%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %&gt; &lt;fmt:formatDate type="date" value="${person. birthDate}" /&gt; </code></pre> <p>But this only works with Java's <code>java.util.Format</code>. What if I need more complex or computed values. In such a case putting the code in the JSP would be cumbersome (and ugly).</p> <p>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?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload