CIS 330: Applied Database Systems Lecture 10: Middle Tier - - PowerPoint PPT Presentation
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
Overview
- Internet concepts
- Three-tier architectures
- The presentation layer
- The middle tier
- CGI
- Application servers
- Servlets
- JSP
- Maintaining state
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!
CGI Overview
Web Browser Web Server C/Perl Program
Name=Ethan Name=Ethan Hello, Ethan! Hello, Ethan!
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.
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.
Overview
- Internet concepts
- Three-tier architectures
- The presentation layer
- The middle tier
- CGI
- Application servers
- Servlets
- JSP
- Maintaining state
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
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
Lecture Overview
- Internet concepts
- Three-tier architectures
- The presentation layer
- The middle tier
- CGI
- Application servers
- Servlets
- JSP
- Maintaining state
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.
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
Servlet Processing Client Request
Web Browser Web Server Java Servlet Database
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.
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.
Server Side Options
§ Common Gateway Interface (CGI) § Fast CGI § Mod Perl § Server Extensions
- NSAPI
- ISAPI
§ ASP § PHP § Cold Fusion
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
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?
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…
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
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
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.
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
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
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.
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.
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
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
Advantages of Servlets
§ Servlets have six main advantages:
- Efficient
- Convenient
- Powerful
- Portable
- Secure
- Inexpensive
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.
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
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.
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.
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.
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.
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
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!”
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
<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.
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.
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 } }
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.
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
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.
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();
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.
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");
} }
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.
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.
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
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.
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.
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>"); } }
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()
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.
Simple Example § The init() method is a good place to put any initialization variables. § For example, the following servlet records its Birth Date/time…
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(); }
// 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();
} }
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.
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()
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!
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.
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.
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!
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.
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 ...
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.
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.
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….
// 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(); } } }
Example rip.txt file
I was destroyed at: Thu Aug 24 11:10:58 CDT 2000
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.
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
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….
// 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….
// 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?
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
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.
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.
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.
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.”
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.
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.
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.
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
<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>
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….
- 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>"); } }
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.
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.
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.
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….
- 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.
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…
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.
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");
- 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" + ….
- 3. Output the HTML