Sie sind auf Seite 1von 41

Web Component Development With Servlet and JSP Technologies Objectives

In this session, you will learn to:


Design a controller component Create an HTML form Describe how HTML form data is sent in the HTTP request Develop a controller servlet Dispatch from a controller servlet to a view servlet

Ver. 1.0

Slide 1 of 41

Web Component Development With Servlet and JSP Technologies Types of Controller Components

Process input from a user Support screen navigation Prepare data for view components

Ver. 1.0

Slide 2 of 41

Web Component Development With Servlet and JSP Technologies Add a New League Analysis Model

Ver. 1.0

Slide 3 of 41

Web Component Development With Servlet and JSP Technologies Add League Boundary Components

Ver. 1.0

Slide 4 of 41

Web Component Development With Servlet and JSP Technologies Add a New League Page Flow

Success path:

Ver. 1.0

Slide 5 of 41

Web Component Development With Servlet and JSP Technologies Add a New League Page Flow (Contd.)

Error path:

Ver. 1.0

Slide 6 of 41

Web Component Development With Servlet and JSP Technologies Form Verification

What are the drawbacks of using server-side verification? What is an alternative to server-side verification? What are the drawbacks of using client-side verification? What is the solution?

Ver. 1.0

Slide 7 of 41

Web Component Development With Servlet and JSP Technologies Soccer League Web Structure

Ver. 1.0

Slide 8 of 41

Web Component Development With Servlet and JSP Technologies Soccer League Web Structure (Contd.)

Ver. 1.0

Slide 9 of 41

Web Component Development With Servlet and JSP Technologies Creating an HTML Form

Ver. 1.0

Slide 10 of 41

Web Component Development With Servlet and JSP Technologies The form Tag

The following is a partial structure of an HTML form:


<form action='URL TO CONTROLLER' method='GET or POST'> <!-- PUT FORM COMPONENT TAGS HERE --> </form>

For example:
<form action=add_league.do method=POST> Year: [textfield tag] Season: [drop-down list tag] Title: [textfield tag] [submit button tag] </form>

A single web page can contain many forms.

Ver. 1.0

Slide 11 of 41

Web Component Development With Servlet and JSP Technologies Textfield Component In Netscape, a textfield component looks like this:

The HTML content for this component is:


16 17 18 19 20 21 <p> This form allows you to create a new soccer league. </p> <form action=add_league.do method=POST> Year: <input type=text name=year /> <br/><br/>

Ver. 1.0

Slide 12 of 41

Web Component Development With Servlet and JSP Technologies Drop-Down List Component

In Netscape, a drop-down list component looks like this:

The HTML content for this component is:


22 Season: <select name=season> 23 <option value=UNKNOWN>select...</option> 24 <option value=Spring>Spring</option> 25 <option value=Summer>Summer</option> 26 <option value=Fall>Fall</option> 27 <option value=Winter>Winter</option> 28 </select> <br/><br/>

Ver. 1.0

Slide 13 of 41

Web Component Development With Servlet and JSP Technologies Submit Button

In Netscape, a submit button component might look like this:

The HTML content for this component is:


29 Title: <input type=text name=title /> <br/><br/> 30 <input type=submit value=Add League /> 31 </form>

Ver. 1.0

Slide 14 of 41

Web Component Development With Servlet and JSP Technologies Complete Add a New League Form
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
Ver. 1.0

<p> This form allows you to create a new soccer league. </p> <form action=add_league.do method=POST> Year: <input type=text name=year /> <br/><br/> Season: <select name=season> <option value=UNKNOWN>select...</option> <option value=Spring>Spring</option> <option value=Summer>Summer</option> <option value=Fall>Fall</option> <option value=Winter>Winter</option> </select> <br/><br/> Title: <input type=text name=title /> <br/><br/> <input type=submit value=Add League /> </form>
Slide 15 of 41

Web Component Development With Servlet and JSP Technologies Form Data in the HTTP Request

HTTP includes a specification for data transmission used to send HTML form data from the web browser to the web server. Syntax:
fieldName1=fieldValue1&fieldName2=fieldValue2&...

Examples:
username=Fred&password=C1r5z season=Winter&year=2004&title=Westminster+Indoor+S occer+(2004)

Ver. 1.0

Slide 16 of 41

Web Component Development With Servlet and JSP Technologies HTTP GET Method Request

Form data is contained in the URL of the HTTP request:


GET /admin/add_league.do?year=2003&season= Winter&title=Westminster+Indoor+HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4) 20030624 Netscape/7.1 Accept: text/xml,application/xml,application/ xhtml+xml,text/html;q=0.9,tex plain;q=0.8,video/xmng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive

Ver. 1.0

Slide 17 of 41

Web Component Development With Servlet and JSP Technologies HTTP POST Method Request

Form data is contained in the body of the HTTP request:


POST /admin/add_league.do HTTP/1.1 Host: localhost:8080 User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4)20030624 Netscape/7.1 Accept: text/xml,application/xml,application/ xhtml+xml,text/html;q=0.9,tex plain;q=0.8,video/xmng,image/png,image/jpeg,image/gif;q=0.2,*/*;q=0.1 Accept-Language: en-us,en;q=0.5 Accept-Encoding: gzip,deflate Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7 Keep-Alive: 300 Connection: keep-alive Referer: http://localhost:8080/controller/ admin/add_league.html Content-Type: application/x-www-form-urlencoded Content-Length: 55 year=2003&season=Winter&title=Westminster+Indoor+S occer
Ver. 1.0

Slide 18 of 41

Web Component Development With Servlet and JSP Technologies HTTP GET and POST Methods

The HTTP GET method is used when:


The processing of the request is idempotent. The amount of form data is small. You want to allow the request to be bookmarked.

The HTTP POST method is used when:


The processing of the request changes the state of the server, such as storing data in a database. The amount of form data is large. The contents of the data should not be visible in the URL (for example, passwords).

Ver. 1.0

Slide 19 of 41

Web Component Development With Servlet and JSP Technologies Developing a Controller Servlet

A form-processing (controller) servlet needs to:


Retrieve form parameters from the HTTP request. Perform any data conversion on the form parameters. Verify the form parameters. Execute the business logic. Dispatch to the next view component based on the results of the previous steps.

Ver. 1.0

Slide 20 of 41

Web Component Development With Servlet and JSP Technologies Add League Analysis Model (Stage 1)

Ver. 1.0

Slide 21 of 41

Web Component Development With Servlet and JSP Technologies Add League Analysis Model (Stage 1) (Contd.)

Ver. 1.0

Slide 22 of 41

Web Component Development With Servlet and JSP Technologies Servlet API to Retrieve Form Parameters

Ver. 1.0

Slide 23 of 41

Web Component Development With Servlet and JSP Technologies The AddLeagueServlet Class Declaration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
Ver. 1.0

package sl314.controller;

import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.ServletException; // Support classes import java.io.IOException; import java.io.PrintWriter; // Model classes import sl314.model.League; import java.util.List; import java.util.LinkedList;
public class AddLeagueServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Keep a set of strings to record form processing errors. List errorMsgs = new LinkedList();
Slide 24 of 41

Web Component Development With Servlet and JSP Technologies Retrieving Form Parameters and Data Conversion
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37

try { // Retrieve form parameters. String yearStr = request.getParameter(year).trim(); String season = request.getParameter(season).trim(); String title = request.getParameter(title).trim();

// Perform data conversions. int year = -1; try { year = Integer.parseInt(yearStr); } catch (NumberFormatException nfe) { errorMsgs.add(The year field must be a positive integer.); }

Ver. 1.0

Slide 25 of 41

Web Component Development With Servlet and JSP Technologies Performing Form Validations
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
Ver. 1.0

// Verify form parameters if((year != -1)&&((year < 2000) || (year > 2010))){ errorMsgs.add(The year field must within 2000 to 2010.); } if ( season.equals(UNKNOWN) ) { errorMsgs.add(Please select a league season.); } if ( title.length() == 0 ) { errorMsgs.add(Please enter the title of the league.); } // Send the ErrorPage view if there were errors if ( ! errorMsgs.isEmpty() ) { // dispatch to the ErrorPage PrintWriter out = response.getWriter(); out.println(ERROR PAGE); return; }
Slide 26 of 41

Web Component Development With Servlet and JSP Technologies Performing the Business Logic
57 58 59 60 61 62 63 64 65

// Perform business logic League league = new League(year, season, title); // Send the Success view PrintWriter out = response.getWriter(); out.println(SUCCESS); return;

Ver. 1.0

Slide 27 of 41

Web Component Development With Servlet and JSP Technologies Handling an Exception
65 66 // Handle any unexpected exceptions 67 } catch (RuntimeException e) { 68 errorMsgs.add(e.getMessage()); 69 // dispatch to the ErrorPage 70 PrintWriter out = response.getWriter(); 71 out.println(ERROR PAGE); 72 73 // Log stack trace 74 e.printStackTrace(System.err); 75 76 } // END of try-catch block 77 } // END of doPost method 78 } // END of AddLeagueServlet class

Ver. 1.0

Slide 28 of 41

Web Component Development With Servlet and JSP Technologies Add League Analysis Model (Stage 2)

Ver. 1.0

Slide 29 of 41

Web Component Development With Servlet and JSP Technologies Add League Architecture Model (Stage 2)

Ver. 1.0

Slide 30 of 41

Web Component Development With Servlet and JSP Technologies Request Scope

Ver. 1.0

Slide 31 of 41

Web Component Development With Servlet and JSP Technologies Using a Request Dispatcher

Ver. 1.0

Slide 32 of 41

Web Component Development With Servlet and JSP Technologies Developing the AddLeagueServlet Code
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Ver. 1.0

import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; // Support classes import java.io.IOException; import java.io.PrintWriter; // Model classes import sl314.model.League; import java.util.List; import java.util.LinkedList; public class AddLeagueServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { // Keep a set of strings to record form processing errors. List errorMsgs = new LinkedList(); // Store this set in the request scope, in case we // need to send the ErrorPage view.
Slide 33 of 41

Web Component Development With Servlet and JSP Technologies Developing the AddLeagueServlet Code (Contd.)
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 request.setAttribute(errorMsgs, errorMsgs);

try {
// Retrieve form parameters. String yearStr = request.getParameter(year).trim(); String season = request.getParameter(season).trim(); String title = request.getParameter(title).trim(); // Perform data conversions. int year = -1; try { year = Integer.parseInt(yearStr); } catch (NumberFormatException nfe) { errorMsgs.add(The year field must be a positive integer.) }

Ver. 1.0

Slide 34 of 41

Web Component Development With Servlet and JSP Technologies Developing the AddLeagueServlet Code (Contd.)
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
Ver. 1.0

// Verify form parameters if((year != -1)&&((year < 2000) || (year > 2010))){ errorMsgs.add(The year field must within 2000 to 2010.); } if ( season.equals(UNKNOWN) ) { errorMsgs.add(Please select a league season.); } if ( title.length() == 0 ) { errorMsgs.add(Please enter the title of the league.); } // Send the ErrorPage view if there were errors if ( ! errorMsgs.isEmpty() ) { RequestDispatcher view = request.getRequestDispatcher(error_page.view); view.forward(request, response); return; }
Slide 35 of 41

Web Component Development With Servlet and JSP Technologies Developing the AddLeagueServlet Code (Contd.)
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
Ver. 1.0

// Perform business logic League league = new League(year, season, title); // Store the new league in the request-scope request.setAttribute(league, league); // Send the Success view RequestDispatcher view = request.getRequestDispatcher(success.view); view.forward(request, response); return; // Handle any unexpected exceptions } catch (RuntimeException e) { errorMsgs.add(e.getMessage()); RequestDispatcher view = request.getRequestDispatcher(error_page.view); view.forward(request, response); // Log stack trace e.printStackTrace(System.err);
Slide 36 of 41

Web Component Development With Servlet and JSP Technologies The SuccessServlet Code
11 12 public class SuccessServlet extends HttpServlet { 13 14 public void doGet(HttpServletRequest request, 15 HttpServletResponse response) 16 throws IOException { 17 generateView(request, response); 18 } 19 20 public void doPost(HttpServletRequest request, 21 HttpServletResponse response) 22 throws IOException { 23 generateView(request, response); 24 } 25 26 public void generateView(HttpServletRequest request, 27 HttpServletResponse response) 28 throws IOException { 29

Ver. 1.0

Slide 37 of 41

Web Component Development With Servlet and JSP Technologies The SuccessServlet Code (Contd.)
30 31 32 33 34 35 36 37 38 39 40 41 // Set page title String pageTitle = Dukes Soccer League: Add League Success; // Retrieve the league from the request -scope League league = (League)request.getAttribute(league); // Specify the content type is HTML response.setContentType(text/html); PrintWriter out = response.getWriter(); // Generate the HTML response out.println(<html>);

Ver. 1.0

Slide 38 of 41

Web Component Development With Servlet and JSP Technologies The SuccessServlet Code (Contd.)
54 55 // Generate main body 56 out.println(<p>); 57 out.print(Your request to add the ); 58 out.print(<i> + league.getTitle() + </i>); 59 out.println( league was successful.); 60 out.println(</p>); 61 62 out.println(</body>); 63 out.println(</html>); 64 65 } // END of generateResponse method 66 67 } // END of SuccessServlet class

Ver. 1.0

Slide 39 of 41

Web Component Development With Servlet and JSP Technologies Demo: Add a New League Page Flow

Demo: Add a New League Page Flow

Ver. 1.0

Slide 40 of 41

Web Component Development With Servlet and JSP Technologies Summary

In this session, you learned:


You can use a controller component to process forms, manage screen navigation, prepare data for views, and so on. You can create web forms using the HTML form tags. Usually, you should use the POST HTTP method to send form data to your servlets. You can access form data on the request stream using the getParameter method on the request object. You can use the request scope to communicate from a controller to a view component. You can use a RequestDispatcher object to forward the request from the controller to the view component.

Ver. 1.0

Slide 41 of 41

Das könnte Ihnen auch gefallen