Differences between revisions 3 and 4
Revision 3 as of 2007-02-21 01:59:01
Size: 2386
Revision 4 as of 2009-09-20 23:12:22
Size: 2395
Editor: localhost
Comment: converted to 1.6 markup
Deletions are marked like this. Additions are marked like this.
Line 7: Line 7:
inline:employee_list.gif {{attachment:employee_list.gif}}
Line 58: Line 58:
[:StrutsQuickStart1:Next: converting servlet-based application into Struts application] [[StrutsQuickStart1|Next: converting servlet-based application into Struts application]]

Employee list with Servlet + JSP (Model 2)

Model 2 offers some benefits over simple Model 1 approach, for example the data-preparation code can be pulled out of JSP file into a servlet, leaving JSP with purely presentation tasks. This makes JSP pages smaller, cleaner and simpler. Also, a servlet can easily swap one presentation with another by changing the name of a JSP page it forwards too. Overall design of Model 2 application is more structured and flexible, though requires more files and more configuration.

This application produces exactly the same employee list as original JSP application.


When request is sent from the browser, the servlet gets called first. It contains all data preparation tasks and looks like this:

{{{public class EmployeeListServlet extends HttpServlet {

  • public void doGet(HttpServletRequest request, HttpServletResponse response)

    • HttpSession session = request.getSession(); // Prepare data for output, store it in the session scope if (session.getAttribute("employees") == null) {

      } // Forward to the JSP page that renders employee list String view = "/jspservlet/employees.jsp";

      RequestDispatcher rd = getServletContext().getRequestDispatcher(view); rd.forward(request, response);


} }}}

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

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


  • <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>






Notice that data access code is removed and the page looks almost like regular HTML. This simplifies making changes to the markup of this page in an HTML editor.

Next: converting servlet-based application into Struts application

StrutsQuickStartServletJSP (last edited 2009-09-20 23:12:22 by localhost)