CIS 330: Applied Database Systems Lecture 10: Middle Tier - - PowerPoint PPT Presentation

cis 330 applied database systems
SMART_READER_LITE
LIVE PREVIEW

CIS 330: Applied Database Systems Lecture 10: Middle Tier - - PowerPoint PPT Presentation

CIS 330: Applied Database Systems Lecture 10: Middle Tier Technologies: Servlets & JSP Alan Demers ademers@cs.cornell.edu Overview Internet concepts Three-tier architectures The presentation layer The middle tier


slide-1
SLIDE 1

CIS 330: Applied Database Systems

Lecture 10: Middle Tier Technologies: Servlets & JSP Alan Demers ademers@cs.cornell.edu

slide-2
SLIDE 2

Overview

  • Internet concepts
  • Three-tier architectures
  • The presentation layer
  • The middle tier
  • CGI
  • Application servers
  • Servlets
  • JSP
  • Maintaining state
slide-3
SLIDE 3

Common Gateway Interface

§ What is CGI?

  • A general framework for creating server side

web applications.

  • Instead of returning a static web document,

web server returns the results of a program.

  • For example

§ browser sends the parameter: name=Ethan. § Web server passes the request to a Perl program. § Perl Program returns HTML that says, Hello, Ethan!

slide-4
SLIDE 4

CGI Overview

Web Browser Web Server C/Perl Program

Name=Ethan Name=Ethan Hello, Ethan! Hello, Ethan!

slide-5
SLIDE 5

Notes on CGI

§ The first mechanism for creating dynamic web sites. § What languages can you create CGI programs in?

  • Unix(tm) fork/exec heritage
  • Just about any language: C/C++, Perl, Java,

etc.

slide-6
SLIDE 6

CGI Environment Variables

§ CGI includes a number of environment variables.

  • REMOTE_ADDR: Address of client browser
  • SERVER_NAME: The Server Host Name or

IP Address

  • SERVER_SOFTWARE: Name and version of

the server software.

  • QUERY_STRING: A String of GET or POST

Form Variables.

  • etc.
slide-7
SLIDE 7

Overview

  • Internet concepts
  • Three-tier architectures
  • The presentation layer
  • The middle tier
  • CGI
  • Application servers
  • Servlets
  • JSP
  • Maintaining state
slide-8
SLIDE 8

Application Servers

  • Idea: Avoid the overhead of CGI
  • Pool of threads / processes
  • Manage connections
  • Enable access to heterogeneous data

sources

  • Other functionality such as APIs for session

management

slide-9
SLIDE 9

Application Server: Process Structure

Process Structure

Web Browser Web Server Application Server C++ Application JavaBeans DBMS 1 DBMS 2 Pool of Servlets HTTP JDBC ODBC

slide-10
SLIDE 10

Lecture Overview

  • Internet concepts
  • Three-tier architectures
  • The presentation layer
  • The middle tier
  • CGI
  • Application servers
  • Servlets
  • JSP
  • Maintaining state
slide-11
SLIDE 11

What is a Servlet?

§ Java’s answer to CGI. § Applet: a java program that runs within the web browser. § Servlet: a java program that runs within the web server. § The current standard for building web applications.

slide-12
SLIDE 12

Servlet Processing Client Request

Regardless of the application, a servlet usually does the following:

2) Read any data sent by the user

  • Capture data submitted by an HTML form.

3) Look up any HTTP information

  • Determine the browser version, host name of client, cookies,

etc.

4) Generate the Results

  • Connect to databases, connect to legacy applications, etc.

5) Format the Results

  • Generate HTML on the fly

6) Set the Appropriate HTTP headers

  • Tell the browser the type of document being returned or set

any cookies.

7) Send the document back to the client

slide-13
SLIDE 13

Servlet Processing Client Request

Web Browser Web Server Java Servlet Database

slide-14
SLIDE 14

What can you build with Servlets?

§ Search Engines § Personalization Systems § E-Commerce Applications § Shopping Carts § Product Catalogs § Intranet Applications § Groupware Applications: bulletin boards, file sharing, etc.

slide-15
SLIDE 15

Server Side Options

§ There are many options for creating server side applications. § We will examine some of these options briefly. § Understand servlets within the broader context of web development. § Understand the advantages and disadvantages of servlets.

slide-16
SLIDE 16

Server Side Options

§ Common Gateway Interface (CGI) § Fast CGI § Mod Perl § Server Extensions

  • NSAPI
  • ISAPI

§ ASP § PHP § Cold Fusion

slide-17
SLIDE 17

Common Features

§ All server side frameworks share a common set of features:

  • Read data submitted by the user
  • Generate HTML dynamically based on user

input

  • Determine information about the client

browser

  • Access Database systems
  • Exploit the HTTP protocol
slide-18
SLIDE 18

Decision Points

§ When evaluating which server side framework to use, you need to consider a number of critical factors:

  • Ease of development:

§ How easily can you build new applications?

  • Performance:

§ How fast can the framework respond to queries?

  • Scalability:

§ Can the framework scale to thousands, millions of users?

  • Security:

§ Are there any inherent security vulnerabilities?

slide-19
SLIDE 19

Option 1: CGI

§ Represents one of the earliest, practical methods for generating web content. § Primarily written in the Perl programming language. § Unfortunately, traditional CGI programs suffer from scalability and performance problems. § Let’s examine these two problems…

slide-20
SLIDE 20

CGI Architecture

1) Browser initiates request 2) Web server receives the request. 3) For each request, web server spawns a new operating system process to execute the CGI/Perl Program. Web Browser Web Server Perl/CGI Create New process

slide-21
SLIDE 21

CGI Architecture

§ For each browser request, the web server must spawn a new operating system process.

Browser 1 Web Server Perl 1 Browser 2 Browser N Perl 2 Perl N

slide-22
SLIDE 22

CGI Architecture

§ Spawning a new operating system process for each request takes time and memory. § Hence, traditional CGI programs have inherent performance and scalability problems. § Every other server architecture tries to address these problems.

slide-23
SLIDE 23

Option 2: Fast CGI

§ Developed by Open Market as an option for developing faster, more scalable CGI programs. § Fast CGI works by creating a pool of processes for handling CGI requests. § When a CGI request comes in, Fast CGI picks one of the processes from the pool and assigns it to the task. § Without the overhead of creating new

  • perating system processes, FastCGI is

much faster than traditional CGI. § See http://www.fastcgi.com

slide-24
SLIDE 24

Option 3: Mod Perl

§ A module of the Apache Web Server (most popular web server on the planet!) § Embeds the Perl interpreter directly within the web server. § Perl programs are precompiled. § Because Perl is embedded within the Server, Mod Perl does not need to create a new process for each request. § Like FastCGI, Mod Perl is much faster than traditional CGI. § See http://perl.apache.org

slide-25
SLIDE 25

Option 4: Server Extensions

§ Several web servers provide extension APIs.

  • Netscape provides NSAPI
  • Microsoft provides ISAPA

§ Much like mod_perl, these programs run directly within the web server. § Hence, server extensions are much faster than traditional CGI. § Usually written in C/C++, and are not portable across web servers. § For example, if you develop to Netscape NSAPI, you cannot run it on ISAPI.

slide-26
SLIDE 26

Option 5: ASP.NET

§ Active Server Pages § Runs on Microsoft’s Web Server: Internet Information Server (IIS) § Programmers add ASP code directly into their HTML pages. § When a client requests a page, the Web Server takes the HTML page, runs the ASP code within the page, and returns a complete HTML page. § Faster than traditional CGI, but only works on Microsoft IIS.

slide-27
SLIDE 27

Option 6: Cold Fusion

§ Developed by Allaire Corporation. § Provides excellent database access and database tools. § Great platform for rapid prototyping and rapid development. § See http://www.allaire.com

slide-28
SLIDE 28

Option 7: PHP

§ Personal Home Pages (PHP) § An open source project written entirely by volunteers § Provides simple, but powerful database access. § Also great for rapid development § Growing very popular § See http://www.php.net

slide-29
SLIDE 29

Advantages of Servlets

§ Servlets have six main advantages:

  • Efficient
  • Convenient
  • Powerful
  • Portable
  • Secure
  • Inexpensive
slide-30
SLIDE 30

Advantage 1: Efficient

§ For each browser request, the servlet spawns a light weight thread. § This is faster and more efficient that spawning a new operating system process. § Hence, servlets have better performance and better scalability than traditional CGI.

slide-31
SLIDE 31

Advantage 2: Convenient

§ Servlets include built-in functionality for:

  • Reading HTML form data
  • Handling cookies
  • Tracking user sessions
  • Setting HTTP headers

§ Java is object oriented

slide-32
SLIDE 32

Advantage 3: Powerful

§ Servlets can talk directly to the web servers. § Multiple servlets can share data:

  • Particularly important for maintaining

database connections.

§ Includes powerful techniques for tracking user sessions.

slide-33
SLIDE 33

Advantage 4: Portable

§ One of the advantages of Java is its portability across different operating systems. § Servlets have the same advantages. § You can write your servlets on Windows, then deploy them on UNIX. § You can run your servlets on any Java- enabled web server, with no code changes.

slide-34
SLIDE 34

Advantage 5: Secure

§ Traditional CGI programs have a number of known security vulnerabilities. § Hence, you usually need to include a separate Perl/CGI module to supply the necessary security protection. § Java has a number of built-in security layers. § Java servlets are considered more secure than traditional CGI programs.

slide-35
SLIDE 35

Advantage 6: Inexpensive

§ You can download free servlet kits for development use. § So you can get started for free! § Nonetheless, production quality servlet web servers can get quite expensive.

slide-36
SLIDE 36

Java Server Pages

§ Related to Java Servlets § Can be used alone or in conjunction with servlets § Represent (yet) another method for creating server side applications

slide-37
SLIDE 37

Servlets v. JSP

§ Servlets

  • code looks like a regular Java program.

§ JSP

  • embed Java commands directly within HTML

§ Let’s examine a Servlet program next to a JSP program… § Each of these prints, “Hello, World!”

slide-38
SLIDE 38

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter();

  • ut.println("<HTML>");
  • ut.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
  • ut.println("<BODY>");
  • ut.println("<BIG>Hello World</BIG>");
  • ut.println("</BODY></HTML>");

} } A Java Servlet : Looks like a regular Java program

slide-39
SLIDE 39

<html> <head> <title>Hello, World JSP Example</title> </head> <body> <h2> Hello, World! The current time in milliseconds is <%= System.currentTimeMillis() %> </h2> </body> </html>

A JSP Page : Looks like a regular HTML page. Embedded Java command to print current time.

slide-40
SLIDE 40

Servlet Template

§ First, let’s take a look at a generic servlet template. § The code does not actually do anything, but all your future servlets will follow this general structure. § The most important pieces are noted in yellow.

slide-41
SLIDE 41

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ServletTemplate extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Use "request" to read incoming HTTP headers // (e.g. cookies) and HTML form data (e.g. data the user // entered and submitted). // Use "response" to specify the HTTP response status // code and headers (e.g. the content type, cookies). PrintWriter out = response.getWriter(); // Use "out" to send content to browser } }

slide-42
SLIDE 42

Generic Template

§ Import the Servlet API:

import javax.servlet.*; import javax.servlet.http.*;

§ To create servlets, you must remember to always use these two import statements.

slide-43
SLIDE 43

Generic Template

§ All your servlets must extend HTTPServlet. § HTTPServlet represents the base class for creating Servlets within the Servlet API. § The Full Servlet API is available at:

  • http://www.java.sun.com/products/servlet/2.2/javadoc/index.html

§ Once you have extended HTTPServlet, you must override one or both:

  • doGet(): to capture HTTP Get Requests
  • doPost(): to capture HTTP Post Requests
slide-44
SLIDE 44

doGet and doPost

§ The doGet() and doPost() methods each take two parameters:

  • HTTPServletRequest: encapsulates all

information regarding the browser request.

§ Form data, client host name, HTTP request headers.

  • HTTPServletResponse: encapsulate all

information regarding the servlet response.

§ HTTP Return status, outgoing cookies, HTML response.

§ If you want the same servlet to handle both GET and POST, you can have doGet call doPost or vice versa.

slide-45
SLIDE 45

Getting an OutputStream

§ The HTTPResponse object has a getWriter() method. § This method returns a java.io.PrintWriter object for writing data out to the Web Browser.

PrintWriter out = response.getWriter();

slide-46
SLIDE 46

Hello World!

§ We are finally ready to see our first real servlet. § This servlet outputs “Hello World!” as plain text, not HTML. § Note: All examples are available on the web site. § Let’s take a look at the code, and then see the servlet in action.

slide-47
SLIDE 47

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter();

  • ut.println("Hello World");

} }

slide-48
SLIDE 48

Output Stream

§ Once you have an OutputStream

  • bject, you just call the println()

method to output to the browser. § Anything you print will display directly within the web browser. § As we will now see, you can also output any HTML tags.

slide-49
SLIDE 49

Generating HTML

§ To generate HTML, you need to add two steps:

  • Tell the browser that you are sending back

HTML.

  • Modify the println() statements to return

valid HTML.

slide-50
SLIDE 50

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWWW extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter();

  • ut.println("<HTML>\n" +

"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n" + "</BODY></HTML>"); } }

Servlet that generates HTML

slide-51
SLIDE 51

Generating HTML

§ To return HTML, you must set the content MIME type to text/html:

  • response.setContentType("text/html");

§ Remember that you must set the content type before you output any content. § Once you have set the MIME type, you can return any HTML document you want.

slide-52
SLIDE 52

Time Servlet

§ Let’s try one more simple servlet… § Using the java.util.Date object, you can

  • btain the current time.

§ Let’s create a simple Servlet that outputs the current time.

slide-53
SLIDE 53

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class TimeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); Date now = new Date(); PrintWriter out = response.getWriter();

  • ut.println("<HTML>\n" +

"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" + "<BODY>\n" + "<H1>Hello WWW</H1>\n"+ "<H2>Time is now: "+now+"</H2>"+ "</BODY></HTML>"); } }

slide-54
SLIDE 54

Servlet Life Cycle

§ Birth: Create and initialize the servlet

  • Important method: init()

§ Life: Handle 0 or more client requests

  • Important method: service()
  • invokes doGet(), doPost(), ...

§ Death: Destroy the servlet

  • Important method: destroy()
slide-55
SLIDE 55

The init() method

§ The init() method is called when the servlet is first requested by a browser request. § It is not called again for each request. § Used for one-time initialization. § There are two versions of the init() method:

  • Version 1: takes no arguments
  • Version 2: takes a servletConfig object as an

argument.

§ We will focus only on the first option.

slide-56
SLIDE 56

Simple Example § The init() method is a good place to put any initialization variables. § For example, the following servlet records its Birth Date/time…

slide-57
SLIDE 57

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Birth extends HttpServlet { Date birthDate; // Init() is called first public void init() throws ServletException { birthDate = new Date(); }

slide-58
SLIDE 58

// Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter();

  • ut.println ("I was born on: "+birthDate);
  • ut.close();

} }

slide-59
SLIDE 59

Life of a Servlet

§ The first time a servlet is called, the Servlet is instantiated, and its init() method is called. § Only one instance of the servlet is instantiated. § This one instance handles all browser requests.

slide-60
SLIDE 60

Service() Method

§ Each time the server receives a request for a servlet, the server spawns a new thread and calls the servlet’s service () method. Browser Browser Browser Web Server Single Instance

  • f Servlet

service() service() service()

slide-61
SLIDE 61

Let’s Prove it…

§ To prove that only one instance of a servlet is created, let’s create a simple example. § The Counter Servlet keeps track of the number of times it has been accessed. § This example maintains a single instance variable, called count. § Each time the servlet is called, the count variable is incremented. § If the Server created a new instance of the Servlet for each request, count would always be 0!

slide-62
SLIDE 62

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Counter extends HttpServlet { // Create an instance variable int count = 0; // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); count++;

  • ut.println ("Since loading, this servlet has "

+ "been accessed "+ count + " times.");

  • ut.close();

} }

Only one instance of the counter Servlet is created. Each browser request is therefore incrementing the same count variable.

slide-63
SLIDE 63

The Service Method

§ By default the service() method checks the HTTP Header. § Based on the header, service calls either doPost() or doGet(). § doPost and doGet is where you put the majority of your code. § If your servlets needs to handle both get and post identically, have your doPost() method call doGet() or vice versa.

slide-64
SLIDE 64

Synchronization

§ The previous example does not really work ...

§ the count instance variable is shared by all threads executing service(). § but accesses to count are not synchronized.

§ This example is just a toy, but there are lots of broken (non-thread-safe) servlets

  • ut there!
slide-65
SLIDE 65

Synchronization

§ By default, multiple threads are executing in the same servlet at the same time. § You therefore need to synchronize access to shared data.

  • For example, what happens if two browsers

request a stock trade for the same account at the same time. § The previous example doesn’t really work ...

  • The count variable is read and updated by

multiple threads with no synchronization. § Synchronization is a large topic, outside the scope of this course.

slide-66
SLIDE 66

SingleThreadModel for Synchronization

§ There is an option called SingleThreadModel § To prevent multi-threaded access, you can have your servlet implement the SingleThreadModel: public class YourServlet extends HttpServlet implements SingleThreadModel { … } § This guarantee that a servlet instance processes only

  • ne browser request at a time.

§ It therefore addresses some (but not all) synchronization issues. § Performance is poor. § Deprecated in Servlets 2.4 on ...

slide-67
SLIDE 67

Death of a Servlet

§ Before a server shuts down, it will call the servlet’s destroy() method.

§ Or maybe just because the server feels like destroying the object ...

§ You can handle any servlet clean up here. For example:

  • Updating log files.
  • Closing database connections.
  • Closing any socket connections.
slide-68
SLIDE 68

Example: Death.java

§ This next example illustrates the use of the destroy() method. § While alive, the servlet will say “I am alive!”. § When the server is stopped, the destroy() method is called, and the servlet records its time of death in a “rip.txt” text file.

slide-69
SLIDE 69

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class Death extends HttpServlet { // Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter();

  • ut.println ("I am alive!");
  • ut.close();

} Continued….

slide-70
SLIDE 70

// This method is called when one stops // the Java Web Server public void destroy() { try { FileWriter fileWriter = new FileWriter ("rip.txt"); Date now = new Date(); String rip = "I was destroyed at: "+now.toString(); fileWriter.write (rip); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }

slide-71
SLIDE 71

Example rip.txt file

I was destroyed at: Thu Aug 24 11:10:58 CDT 2000

slide-72
SLIDE 72

A Persistent Counter

§ Now that we know all about the birth, life and death of a servlet, let’s put this knowledge together to create a persistent counter. § The Counter.java example we covered earlier has a big problem:

  • When you restart the web server, counting

starts all over at 0.

  • It does not retain any persistent memory.
slide-73
SLIDE 73

Persistent Counter

§ To create a persistent record, we can store the count value within a “counter.txt” file.

  • init(): Upon start-up, read in the current

counter value from counter.txt.

  • destroy(): Upon destruction, write out the

new counter value to counter.txt

slide-74
SLIDE 74

import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class CounterPersist extends HttpServlet { String fileName = "counter.txt"; int count; public void init () { try { FileReader fileReader = new FileReader (fileName); BufferedReader bufferedReader = new BufferedReader (fileReader); String initial = bufferedReader.readLine(); count = Integer.parseInt (initial); } catch (FileNotFoundException e) { count = 0; } catch (IOException e) { count = 0; } catch (NumberFormatException e) { count = 0; } }

At Start-up, load the counter from file. In the event of any exception, initialize count to 0. Continued….

slide-75
SLIDE 75

// Handle an HTTP GET Request public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); PrintWriter out = response.getWriter(); count++;

  • ut.println ("Since loading, this servlet has "

+"been accessed "+ count + " times.");

  • ut.close();

}

Each time the doGet() method is called, increment the count variable. Continued….

slide-76
SLIDE 76

// At Shutdown, store counter back to file public void destroy() { try { FileWriter fileWriter = new FileWriter (fileName); String countStr = Integer.toString (count); fileWriter.write (countStr); fileWriter.close(); } catch (IOException e) { e.printStackTrace(); } } }

When destroy() is called, store new counter variable back to counter.txt. Can anybody foresee any problems with this code?

slide-77
SLIDE 77

Road Map

§ Overview of Browser/Servlet Communication § Reading Form Data from Servlets § Example 1: Reading three parameters § Example 2: Reading all parameters § Case Study: Resume Posting Service

slide-78
SLIDE 78

Client Request Data

§ When a user submits a browser request to a web server, it sends two categories of data:

  • Form Data: Data that the user explicitly typed into an

HTML form.

§ For example: registration information.

  • HTTP Request Header Data: Data that is

automatically appended to the HTTP Request from the client.

§ For example: cookies, browser type, browser IP address.

§ This part examines Form Data; the next part examines HTTP Data.

slide-79
SLIDE 79

Form Data

§ Based on our understanding of HTML, we now know how to create user forms. § We also know how to gather user data via all the form controls: text, password, select, checkbox, radio buttons, etc. § Now, the question is: if I submit form data to a servlet, how do I extract this form data? § Figuring this out forms the basis of creating interactive web applications that respond to user requests.

slide-80
SLIDE 80

Reading Form Data from Servlets

§ The HttpServletRequest object contains three main methods for extracting form data:

  • getParameter(): used to retrieve a single form

parameter.

  • getParameterValues(): used to retrieve a list of

form values, e.g. a list of selected checkboxes.

  • getParameterNames(): used to retrieve a full list
  • f all parameter names submitted by the user.

§ We will examine each of these and then explore several examples.

slide-81
SLIDE 81

Reading Form Data

§ All these methods work the same way regardless of whether the browser uses HTTP GET or HTTP POST. § Remember that form elements are case

  • sensitive. Therefore, “userName” is not

the same as “username.”

slide-82
SLIDE 82

getParameter() Method

§ Used to retrieve a single form parameter. § Possible return values:

  • String: corresponds to the form parameter.
  • Empty String: parameter exists, but has no

value.

  • null: parameter does not exist.
slide-83
SLIDE 83

getParameterValues() Method

§ Used to retrieve multiple form parameters with the same name. § For example, a series of checkboxes all have the same name, and you want to determine which ones have been selected. § Returns an Array of Strings.

  • An array with a single empty string indicates that the

form parameter exists, but has no values.

  • null: indicates that the parameter does not exist.
slide-84
SLIDE 84

getParameterNames() method

§ Returns an Enumeration object. § By cycling through the enumeration

  • bject, you can obtain the names of all

parameters submitted to the servlet. § Note that the Servlet API does not specify the order in which parameter names appear.

slide-85
SLIDE 85

Example 1

§ Our first example consists of one HTML page, and one servlet. § The HTML page contains three form parameters: param1, param2, and param3. § The Servlet extracts these specific parameters and echoes them back to the browser. § Before we examine the code, let’s try it out:

http://ecerami.com/applied_fall_2000/examples/servlets/ThreeParamsForm.html

slide-86
SLIDE 86

<HTML> <HEAD> <TITLE>Collecting Three Parameters</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <H1 ALIGN="CENTER">Collecting Three Parameters</H1> <FORM ACTION="/servlet/coreservlets.ThreeParams"> First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR> Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR> Third Parameter: <INPUT TYPE="TEXT" NAME="param3"><BR> <CENTER> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY> </HTML>

slide-87
SLIDE 87

package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /** Simple servlet that reads three parameters from the * form data. */ public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading Three Request Parameters";

Continued….

slide-88
SLIDE 88
  • ut.println(ServletUtilities.headWithTitle(title) +

"<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<UL>\n" + " <LI><B>param1</B>: " + request.getParameter("param1") + "\n" + " <LI><B>param2</B>: " + request.getParameter("param2") + "\n" + " <LI><B>param3</B>: " + request.getParameter("param3") + "\n" + "</UL>\n" + "</BODY></HTML>"); } }

slide-89
SLIDE 89

Example 2

§ Example 1 will only read explicit parameters. § Now, let’s look at a Servlet that echoes back all the form parameters you send it.

slide-90
SLIDE 90

Example 2

§ The Example works by first calling getParameterNames(). § By cycling through the returned Enumeration, the servlet can access all form names. § For each form name, we call getParameterValues() to extract the form values. § By cycling through the returned array of strings, we then print out all the associated values.

slide-91
SLIDE 91

package coreservlets; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class ShowParameters extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String title = "Reading All Request Parameters";

  • ut.println(ServletUtilities.headWithTitle(title) +

"<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Parameter Name<TH>Parameter Value(s)");

Continued…. Output a simple HTML table for displaying the form parameters.

slide-92
SLIDE 92

Enumeration paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement();

  • ut.print("<TR><TD>" + paramName + "\n<TD>");

String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0)

  • ut.println("<I>No Value</I>");

else

  • ut.println(paramValue);

} else {

  • ut.println("<UL>");

for(int i=0; i<paramValues.length; i++) {

  • ut.println("<LI>" + paramValues[i]);

}

  • ut.println("</UL>");

} }

  • 1. First, use

getParameterNames() to retrieve an Enumeration

  • f all form parameters.
  • 2. Then, iterate through

each element within the Enumeration. Continued….

slide-93
SLIDE 93
  • ut.println("</TABLE>\n</BODY></HTML>");

} public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

doPost calls doGet(). Therefore the servlet will work just as well for HTTP POSTs or GETs.

slide-94
SLIDE 94

Resume Posting Service

§ Our next servlet receives a series of parameters:

  • Name, title, email address, programming

languages.

  • Font, font size, etc.

§ Based on these parameters, the user is able to post his/her resume online. § Let’s first try it out…

slide-95
SLIDE 95

SubmitResume.java

§ Three major sections to SubmitResume.java

  • Retrieve all the form parameters.
  • Make the style sheet
  • Output the HTML for the resume.

§ We will examine each piece. For the full code, see today’s handout.

slide-96
SLIDE 96

1.Retrieving Form Parameters § First, the showPreview() method retrieves the form parameters. § If a parameter is missing, we supply a default: String fgColor = request.getParameter("fgColor");

fgColor = replaceIfMissing(fgColor, "BLACK"); String bgColor = request.getParameter("bgColor"); bgColor = replaceIfMissing(bgColor, "WHITE");

slide-97
SLIDE 97
  • 2. Make the Style Sheet

§ Based on the form parameters, we create an appropriate stylesheet via the makeStyleSheet() method:

String styleSheet = "<STYLE TYPE=\"text/css\">\n" + "<!--\n" + ".HEADING1 { font-size: " + heading1Size + "px;\n" + " font-weight: bold;\n" + " font-family: " + headingFont + "Arial, Helvetica, sans-serif;\n" + "}\n" + ….

slide-98
SLIDE 98
  • 3. Output the HTML

§ The showPreview() method outputs SPAN tags plus resume data:

… "<CENTER>\n"+ "<SPAN CLASS=\"HEADING1\">" + name + "</ SPAN><BR>\n" + "<SPAN CLASS=\"HEADING2\">" + title + "<BR>\n" + "<A HREF=\"mailto:" + email + "\">" + email + "</A></SPAN>\n" + "</CENTER><BR><BR>\n" + …