In Spring / JSP, where should formatting be done?

I use Spring, but this question applies to all types of JSP controller constructs.

The JSP page refers to data (using tags) that is populated by the appropriate controller. My question is: where is the appropriate place to format, in the JSP or controller?

So far I have been preparing 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 one field
        properties.put("location", person.getLatitude() + ", " + person.getLongitude());

        return new ModelAndView("viewPerson", "person", properties);
    }
}

The JSP file will look something like this:

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 has 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 java.util.Format. What if I need more complex or calculated values. In this case, entering code into the JSP would be cumbersome (and ugly).

, Spring/JSP/MVC. , ? , ? (Person) ?

+5
4

JSP ( ?) ,

, , , , , , , .

, , .

+5

.. bean "". , :

  • , , .
  • .
+1

, , JSP. Velocity , JSP: controller , . JSP .

. , , , , , . , , , . , , , .

+1

-

Person Model ModelAndView

" " Person. ,

public class Person {
    public String getLocation() {
        return this.latitude.concat(", ").concat(this.longitude);
    }
}

I think that overall this approach: 1 - strengthens your domain model. 2 - reduces code duplication (what if you want to show the location in another JSP? With your approach, you will have a lot of duplicate code)

0
source

All Articles