Java Reference
In-Depth Information
In Listing 14‐3, the
ListUserAction
's execute method constructs a list of users that it adds as
an attribute to the request object; then it returns the location of the view to render and display
to the user. The data now stored in the request object is accessed by the
listuser.jsp
page and
displayed.
For brevity, a
List
object has been populated and returned, but in a real application, this is where
you would use EJB or other data objects that connect to a database.
LISTING 14‐3:
The Action class
package com.devchronicles.mvc.plain;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ListUsersAction implements Action {
public String execute(HttpServletRequest request, HttpServletResponse
response) {
List<String> userList = new ArrayList<>();
userList.add("John Lennon");
userList.add("Ringo Starr");
userList.add("Paul McCartney");
userList.add("George Harrison");
request.setAttribute("listusers", userList);
return "/WEB-INF/pages/listusers.jsp";
}
}
object returns to the controller, which receives the location of the page to which it
should dispatch the request and response objects.
String view = action.execute(request, response);
getServletContext().getRequestDispatcher(view).forward(request, response);
The
Action
In Listing 14‐4, the JSP accesses the page's
requestScope
variable and retrieves the
userList
list
object created in
ListUserAction
. It then iterates over the collection and displays the usernames.
LISTING 14 ‐ 4:
The listuser.jsp access generates the page the user requested
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@ taglib uri="
http://java.sun.com/jsp/jstl/core"
prefix ="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
continues