advanced internet technology lab # 5site.iugaza.edu.ps/djabal/files/ait-lab-5.pdf2 advanced internet...
TRANSCRIPT
Faculty of EngineeringComputer Engineering Department
Islamic University of Gaza
Eng. Doaa Abu Jabal
2011
Advanced Internet Technology Lab # 5Handling Client Requests
2
Advanced Internet TechnologyLab # 5
Handling Client Requests
Objective:
To be familiar with Servlet Concepts.
Topics
• Handling Client Requests
Handling Client Requests
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. HTTP Request Header Data: Data that is automatically appended to the HTTP Request from the
client. For example: cookies, browser type, browser IP address.
Form Elements
Form elements are elements that allow the user to enter information in a form.
The famous form elements are:
1- Text Fields<input type="text" name="firstname" />
2- Radio Buttons<input type="radio" name="sex" value="male" /> Male
3- Checkboxes<input type="checkbox" name="vehicle" value="Bike" />
4- Drop down list<select name="cars">
<option value="volvo">Volvo</option>
3
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
5- Multiple drops down list<select name="state" size="5" mulpl e>
<option value="NJ">New Jersey</option>
<option value="NY">New York</option>
<option value="KS">Kansas</option>
<option value="CA">California</option>
<option value="TX">Texas</option>
</select>
6- Text area<textarea name="address" rows=3 cols=40></textarea >
7- Password text field<input type="password" NAME="pass">
Reading Form Data from Servlets
• The HttpServletRequest object contains three main methods for extracting form data:
• getParameter( “paramName” ): used to retrieve a single form parameter.
• getParameterValues( “paramName” ): used to retrieve a list of form values, e.g. a list ofselected checkboxes.
• getParameterNames(): used to retrieve a full list of all parameter names submitted by theuser.
• All these methods work the same way regardless of whether the browser uses HTTP GET orHTTP POST.
• Remember that form elements are case sensitive. Therefore, “userName” is not the same as“username.”
4
getParameter() Method
This 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
This method Used to retrieve multiple form parameters with the same name. For example, a seriesof 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 parameterexists, but has no values).
• null: indicates that the parameter does not exist.
getParameterNames() method
This method returns an Enumeration object. By cycling through the enumeration object, you canobtain the names of all parameters submitted to the Servlet.
Example 1 – Reading Three parameters
This 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.
ThreeParameters.html
<HTML>
<HEAD>
<TITLE>Three Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">Collecting Three Parameters</H1>
5
<FORM ACTION="/HelloServlet/ThreeParams" method=post>
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>
Second Parameter: <INPUT TYPE="TEXT" NAME="param2"><BR>
Third Parameter: <INPUT TYPE="PASSWORD" NAME="param3"><BR>
<INPUT TYPE="SUBMIT">
</FORM>
</BODY>
</HTML>
ThreeParams.java
package lab5;
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, HttpServletResponseresponse) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
6
out.println( "<html> <head>"
+"<title>Processing get requests with data</title></head>"+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>Reading Three Request Parameters</H1>\n"+
"<UL>\n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "</LI>\n" +
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "</LI>\n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "</LI>\n" +
"</UL>\n" +
"</BODY></HTML>");
}
public void doPost(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {
doGet(request,response);
}
}
Example 2- Reading all parameters
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.
7
ShowParameters.java
package lab5;
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();
out.println("<HTML>\n" +
"<HEAD><TITLE>Reading All Request Parameters </TITLE></HEAD>\n"+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>Reading All Request Parameters</H1>\n"+
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Parameter Name</TH><TH>Parameter Value(s)</TH></TR>");
8
Enumeration paramNames = request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("\n<TR>\n<TD>" + paramName + "</TD>\n<TD>");
String[] paramValues = request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out.print("\n<I>No Value</I>\n");
else
out.print(paramValue);
} else{
out.print("\n<UL>");
for(int i=0; i<paramValues.length; i++) {
out.print("\n<LI>" + paramValues[i]+ "</LI>");
}
out.print("\n</UL>");
}
out.print("\n</TD>\n</TR>");
}
out.println("</TABLE>\n</BODY></HTML>");
}
9
public void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
doGet(request, response);
}
}
form.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head><title>A Sample FORM using POST</title></head>
<body BGCOLOR="#FDF5E6">
<h1 ALIGN="CENTER">A Sample FORM using POST</h1>
<form action="/HelloServlet/ShowParameters" METHOD="POST">
Item Number: <INPUT TYPE="TEXT" NAME="itemNum"><BR>
Description: <INPUT TYPE="TEXT" NAME="description"><BR>
Price Each: <INPUT TYPE="TEXT" NAME="price" VALUE="$"><BR>
<HR>
First Name: <INPUT TYPE="TEXT" NAME="firstName"><BR>
Last Name: <INPUT TYPE="TEXT" NAME="lastName"><BR>
Middle Initial: <INPUT TYPE="TEXT" NAME="initial"><BR>
Shipping Address:
<TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
Credit Card:<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Visa">Visa<BR>
<INPUT TYPE="RADIO" NAME="cardType"
10
VALUE="MasterCard">MasterCard<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Amex">American Express<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Discover">Discover<BR>
<INPUT TYPE="RADIO" NAME="cardType"
VALUE="Java SmartCard">Java SmartCard<BR>
Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
Repeat Credit Card Number:
<INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR>
<CENTER><INPUT TYPE="SUBMIT" VALUE="Submit Order"></CENTER>
</FORM>
</BODY>
</HTML>
Reading HTTP Request Headers
Reading headers is straightforward; just call the getHeader method of HttpServletRequestwith the name of the header.
This call returns
1- A String if the specified header was supplied in the current request2- null otherwise.Note: header names are not case sensitive.
The most famous headers are:
1- Date: Specifies the current time at the server.2- Expires: Specifies the time when the content can be considered stale.3- Last-Modified: Specifies the time when the document was last modified.4- Refresh: Tells the browser to reload the page.
Although getHeader is the general-purpose way to read incoming headers, a few headers areso commonly used that they have special access methods in HttpServletRequest.
11
Following is a summary:
• getMethod• getProtocol• getContentLength• getContentType
• getDateHeader and getIntHeader• getHeaderNames• getHeaders
In addition to looking up the request headers, you can get information on the main requestline itself, also by means of methods in HttpServletRequest. Here is a summary of the fivemain methods.
• getContextPath• getRequestURI• getQueryString• getPathInfo• getServletPath
For example, for a URL of http://randomhost.com/servlet/BookSearch?subject=jsp, getRequestURI would return "/servlet/BookSearch"
Context Path, Servlet path and path info will coming on Respectively. getQueryString
would return everything after question mark "subject=jsp"
Request URI = context path + servlet path + path info.
Example 3
This example echoes all of the HTTP Request Information. First, it outputs:
• Context Path• Request URI• Query String• Path Info• Servlet Path
Then, it calls getHeaderNames() to retrieve a list of all HTTP Header Names.For each header name, itthen calls getHeader()
package lab5;
import java.io.*;
import javax.servlet.*;
12
import javax.servlet.http.*;
import java.util.*;
public class ShowRequestHeaders extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException,IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html> <head>" +
"<title>Servlet Example: Showing Request Headers</title> </head>"+
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>Servlet Example: Showing Request Headers</H1>\n" +
"<B>Request URI: </B>" + request.getRequestURI() + "<BR>\n" +
"<B>Request Context Path: </B>" +request.getContextPath() + "<BR>\n"+
"<B>Request Servlet Path:</B>"+request.getServletPath()+"<BR>\n" +
"<B>Request Path Info:</B>"+request.getPathInfo()+"<BR>\n" +
"<B>Request Query String:</B>"+request.getQueryString()+"<BR><BR>\n"+
"<TABLE BORDER=1 ALIGN=CENTER>\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" +
"<TH>Header Name<TH>Header Value");
Enumeration headerNames = request.getHeaderNames();
13
while(headerNames.hasMoreElements()) {
String headerName = (String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println(" <TD>" + request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
}
/** Let the same servlet handle both GET and POST. */
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}