21
COMP 321 COMP 321 Week 8 Week 8

COMP 321 Week 8. Overview MVC Example Servlet Lifecycle Servlet Mechanics MVC Lab 5-2 Solution Lab 8-1 Introduction

Embed Size (px)

Citation preview

COMP 321COMP 321

Week 8Week 8

OverviewOverview

MVC ExampleMVC Example

Servlet LifecycleServlet Lifecycle

Servlet MechanicsServlet Mechanics

MVCMVC

Lab 5-2 SolutionLab 5-2 Solution

Lab 8-1 IntroductionLab 8-1 Introduction

MVC ExampleMVC Example

MVC ExampleMVC Example

Displaying the FormDisplaying the Form

1.1. Client makes a request for form.htmlClient makes a request for form.html

2.2. Container retrieves the form.html pageContainer retrieves the form.html page

3.3. Container returns page to the browser, User answers Container returns page to the browser, User answers questions and submitsquestions and submits

Displaying ResultsDisplaying Results

4.4. Browser sends request data Browser sends request data to containerto container

5.5. Container finds servlet based Container finds servlet based on URL, and forwards requeston URL, and forwards request

6.6. Servlet calls BeerExpert for Servlet calls BeerExpert for helphelp

7.7. Expert class returns an Expert class returns an answer, which servlet adds to answer, which servlet adds to request objectrequest object

8.8. Servlet forwards request to Servlet forwards request to JSPJSP

9.9. JSP gets answer from request JSP gets answer from request objectobject

10.10. JSP generates pageJSP generates page

11.11. Container returns page to Container returns page to useruser

Development File StructureDevelopment File Structure

Deployment File StructureDeployment File Structure

Form HTMLForm HTML<html><body><h1 align="center">Beer Selection Page</h1><form method="POST" action="SelectBeer.do"> Select beer characteristics<p> Color: <select name="color" size="1"> <option value="light">light</option> <option value="amber">amber</option> <option value="brown">brown</option> <option value="dark">dark</option> </select> <br><br> <center> <input type="SUBMIT"> </center></form></body></html>

Deployment DescriptorDeployment Descriptor<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" version="2.4">

<servlet> <servlet-name>Ch3 Beer</servlet-name> <servlet-class>com.example.web.BeerSelect</servlet-class> </servlet>

<servlet-mapping> <servlet-name>Ch3 Beer</servlet-name> <url-pattern>/SelectBeer.do</url-pattern> </servlet-mapping>

</web-app>

Servlet Code (Version #1)Servlet Code (Version #1)// Version 1public class BeerSelect extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");

PrintWriter out = response.getWriter();

out.println("Beer Selection Advice<br>");

// For now, just show selected color so we can test servlet deployment String c = request.getParameter("color"); out.println("<br>Got beer color " + c); }}

Model ClassModel Classpublic class BeerExpert { public List getBrands(String color) { List brands = new ArrayList(); if(color.equals("amber")) { brands.add("Jack Amber"); brands.add("Red Moose"); } else { brands.add("Jail Pale Ale"); brands.add("Gout Stout"); }

return brands; }}

Servlet Code (Version #2)Servlet Code (Version #2)public class BeerSelect extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String c = request.getParameter("color"); BeerExpert be = new BeerExpert(); List result = be.getBrands(c);

response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("Beer Selection Advice<br>");

Iterator it = result.iterator(); while(it.hasNext()) { out.print("<br>try: " + it.next()); } }}

Current FlowCurrent Flow

1.1. The browser sends the The browser sends the request data to the request data to the ContainerContainer

2.2. The Container finds the The Container finds the correct Servlet based correct Servlet based on the URL, and on the URL, and passes the request to passes the request to the Servlet.the Servlet.

3.3. The Servlet calls the The Servlet calls the BeerExpert for help.BeerExpert for help.

4.4. The expert class The expert class returns an answer.returns an answer.

5.5. The Container returns The Container returns the page to the happy the page to the happy user.user.

Dispatching to the JSPDispatching to the JSP// Version 3public class BeerSelect extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String c = request.getParameter("color"); BeerExpert be = new BeerExpert(); List result = be.getBrands(c);

request.setAttribute("styles", result);

RequestDispatcher view = request.getRequestDispatcher("result.jsp");

view.forward(request, response); }}

……and in the JSP…and in the JSP…<%@ page import="java.util.*" %><html><body><h1 align="center">Beer Recommendations JSP</h1><p>

<% List styles = (List)request.getAttribute("styles"); Iterator it = styles.iterator(); while(it.hasNext()) { out.print("<br>try: " + it.next()); }%>

</body></html>

Servlet LifecycleServlet Lifecycle

Container loads classContainer loads class

Container creates instanceContainer creates instance

Container calls init()Container calls init()

Container calls service() each time a Container calls service() each time a request comes inrequest comes in

Container calls destroy()Container calls destroy()

Servlet APIServlet APIpublic interface Servlet {

void init(ServletConfig config);

void service(ServletRequest request, ServletResponse response);

void destroy();

...

}

public abstract class GenericServlet implements Servlet {

// Implements init(), service(), destroy()

}

public abstract class HttpServlet extends GenericServlet {

void service(ServletRequest req, ServletResponse resp) { … }

protected void service(HttpServletRequest req, HttpServletResponse resp) { … }

protected void doGet(HttpServletRequest req, HttpServletResponse resp) { … }

protected void doPost(HttpServletRequest req, HttpServletResponse resp) { … }

}

How to Write a Servlet – How to Write a Servlet – Programming TipsProgramming Tips

Don’t do anything in the constructor – the Don’t do anything in the constructor – the object isn’t really a servlet yet!object isn’t really a servlet yet!

Initialization belongs in init()Initialization belongs in init()

Servlet is given a Servlet is given a ServletConfigServletConfig and a and a ServletContextServletContext - pay attention to the - pay attention to the differencedifference

Each request is made on a separate Each request is made on a separate thread, but they all use thread, but they all use the same objectthe same object

Lab 8-1 Servlets IntroductionLab 8-1 Servlets Introduction

Progress CheckProgress Check

Due this week:Due this week: Lab 7-1 Preparing to Build Web ApplicationsLab 7-1 Preparing to Build Web Applications

Due next week:Due next week: Begin working on Lab 8-1 ServletsBegin working on Lab 8-1 Servlets