You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@struts.apache.org by Apache Wiki <wi...@apache.org> on 2007/02/21 01:33:29 UTC

[Struts Wiki] Update of "StrutsQuickStartServletJSP" by MichaelJouravlev

Dear Wiki user,

You have subscribed to a wiki page or wiki category on "Struts Wiki" for change notification.

The following page has been changed by MichaelJouravlev:
http://wiki.apache.org/struts/StrutsQuickStartServletJSP

New page:
== Employee list with pure Servlet + JSP (Model 2) ==

One can argue that JSTL 2.0 greatly simplifies access to dynamic data from JSP, therefore pure JSP applications look less cluttered. Nevertheless, Model 2 allows additional benefits. With Model 2 approach, the data-preparation code is located in a servlet, while JSP performs purely presentation tasks. This makes JSP pages smaller, cleaner and simpler. Also, a servlet may easily replace one presentation with another by changing the name of a JSP page it forwards too. Overall design is more structured.

Here is how the servlet would look like:

{{{public class EmployeeListServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException
    {
        HttpSession session = request.getSession();

        // Prepare data for output
        if (session.getAttribute("employees") == null) {
            session.setAttribute("employees", EmployeeManager.loadEmployees());
        }

        // Forward to the JSP page that renders employee list
        String view = "/jspservlet/employees.jsp";
        RequestDispatcher rd = getServletContext().getRequestDispatcher(view);
        rd.forward(request, response);
    }
}
}}}

The request is processed by the servlet, then the servlet forwards to "/jspservlet/employees.jsp" page, which displays the result:

{{{<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
  <body>
    <table>
      <tr>
        <th align="left">Emp #</th>
        <th align="left">Name</th>
        <th align="left">Salary</th>
      </tr>
      <c:forEach var="employee" items="${employees}">
        <tr>
          <td>${employee.id}</td>
          <td>${employee.name}</td>
          <td>${employee.salary}</td>
        </tr>
      </c:forEach>
    </table>
  </body>
</html>}}}