Question

Considering a Servlet and a simple JSP page.

I would like to reduce as possible coupling, between my presentation and my application and I would like to reduce as possible Java code in my JSP page.

I have a simple HTML list filled with Java, in my JSP page.

  <%
  String[] myList = (String[])request.getAttribute("myList");
  %>

  <form name="selection" action="foo.jsp">
       <select name="myList">
           <option value=""> </option>
           <% for (int i = 0; i < myList.length; i++){%>
               <option value="<%=i%>"><%=myList[i]%></option>
           <%}%>
       </select>
       <input type="submit" />
   </form>

What's the best way/pattern to use, to reduce as possible Java code (loop) in the presentation? The problem would not be better by generating html directly in the servlet.

Edit: I am looking for a solution in the doGet() servlet method.

Was it helpful?

Solution

You could use JSTL to clean up the logic in your JSP page. You could use patterns like MVC to make your backend design better.

In fact for the current code you have simply JSTL would more than suffice but as complexity grows you might want to explore frameworks like Spring, Struts or EJBs for a more robust and cleaner separation of concerns and long term maintainability.

In you case for instance the JSTL equivalent would be something like:

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core" %>

  <form name="selection" action="foo.jsp">
       <select name="myList">
           <option value=""> </option>
       <c:forEach var="item" items="${myList}"  varStatus="status">
          <option value='<c:out value="${status.index}"/>'><c:out value="${item}" /></option>
           </c:forEach>           
       </select>
       <input type="submit" />
   </form>

Some Notes:

To some extent you are already following part of MVC pattern in that you are not adding any business logic in your view(JSP) but simply utilizing the model(myItems) to paint the view. How the model was constructed, and what business logic was executed is kept separate from view.

And to your point of reducing java code, the view functions to simply utilize the model to render the presentation to the user. Instead of code it helps to utilize view frameworks/libraries to render the model. This is done by many people by utilizing JSTL within your JSPs, using alternative templating frameworks like Velocity etc or even completely front end javascript templating like underscore etc.

Some Links:

JSTL Tutorial: http://www.tutorialspoint.com/jsp/jsp_standard_tag_library.htm

JSTL @ Java.net: https://jstl.java.net/

MVC Pattern: http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller

Spring Framework: http://www.springsource.org/spring-framework

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top