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)
throws IOException, ServletException
HttpSession session = request.getSession(); // Prepare data for output, store it in the session scope if (session.getAttribute("employees") == null) {
session.setAttribute("employees", EmployeeManager.loadEmployees());
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" %>
<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>}}}
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