Title: Servlets: Servlet / Web Browser Communication I
1ServletsServlet / Web Browser Communication I
2Road 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
- Security Filtering User Input
3Note Change in Syllabus
- Core Servlets, Chapter 4 (skip sections 4.7 -
4.8)
4Overview of Browser/Servlet Communication
5Overview
- This lecture is the first in two lectures that
discuss the interaction between web browsers and
servlets.
Request
Web Browser
Web Server
Response
6Client 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 lecture examines Form Data the next lecture
examines HTTP Data.
7Form Data
8Form 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.
9Reading 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 of all parameter names submitted by the
user. - We will examine each of these and then explore
several examples.
10Reading 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.
11getParameter() 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.
12getParameterValues() 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.
13getParameterNames() method
- Returns an Enumeration object.
- By cycling through the enumeration object, 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.
14Example 1 Reading three explicit parameters
15Example 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, lets try it out
16ltHTMLgt ltHEADgt ltTITLEgtCollecting Three
Parameterslt/TITLEgt lt/HEADgt ltBODY
BGCOLOR"FDF5E6"gt ltH1 ALIGN"CENTER"gtCollecting
Three Parameterslt/H1gt ltFORM ACTION"/servlet/core
servlets.ThreeParams"gt First Parameter ltINPUT
TYPE"TEXT" NAME"param1"gtltBRgt Second
Parameter ltINPUT TYPE"TEXT" NAME"param2"gtltBRgt
Third Parameter ltINPUT TYPE"TEXT"
NAME"param3"gtltBRgt ltCENTERgt ltINPUT
TYPE"SUBMIT"gt lt/CENTERgt lt/FORMgt lt/BODYgt lt/HTML
gt
17package 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.
18 out.println(ServletUtilities.headWithTitle(ti
tle) "ltBODY BGCOLOR\"FDF5E6\"gt
\n" "ltH1 ALIGNCENTERgt" title
"lt/H1gt\n" "ltULgt\n"
" ltLIgtltBgtparam1lt/Bgt "
request.getParameter("param1") "\n"
" ltLIgtltBgtparam2lt/Bgt "
request.getParameter("param2") "\n"
" ltLIgtltBgtparam3lt/Bgt "
request.getParameter("param3") "\n"
"lt/ULgt\n"
"lt/BODYgtlt/HTMLgt") Lets run this example
19Example 2 Reading all Parameters
20Example 2
- Example 1 will only read explicit parameters.
- Now, lets look at a Servlet that echoes back all
the form parameters you send it.
21Example 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.
22package coreservlets import java.io. import
javax.servlet. import javax.servlet.http. impo
rt 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"
out.println(ServletUtilities.headWithTitle(titl
e) "ltBODY BGCOLOR\"FDF5E6\"gt\n
" "ltH1 ALIGNCENTERgt" title
"lt/H1gt\n" "ltTABLE BORDER1
ALIGNCENTERgt\n" "ltTR
BGCOLOR\"FFAD00\"gt\n"
"ltTHgtParameter NameltTHgtParameter Value(s)")
Output a simple HTML table for displaying the
form parameters.
Continued.
23 Enumeration paramNames request.getParameterN
ames() while(paramNames.hasMoreElements())
String paramName (String)paramNames.next
Element() out.print("ltTRgtltTDgt" paramName
"\nltTDgt") String paramValues
request.getParameterValues(paramName) if
(paramValues.length 1) String
paramValue paramValues0 if
(paramValue.length() 0)
out.println("ltIgtNo Valuelt/Igt") else
out.println(paramValue) else
out.println("ltULgt") for(int i0
iltparamValues.length i)
out.println("ltLIgt" paramValuesi)
out.println("lt/ULgt")
- First, use getParameterNames() to retrieve an
Enumeration of all form parameters. - Then, iterate through each element within the
Enumeration.
Continued.
24 out.println("lt/TABLEgt\nlt/BODYgtlt/HTMLgt")
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.
25Lets run this example from the web
26Case Study Resume Posting Service
27Resume 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. - Lets first try it out
28Cascading Style Sheets
- The Resume servlet utilizes Cascading Style
Sheets (CSS). - We have not covered CSS but, we will cover the
very basics right now. - Lets begin with a brief description of CSS.
29CSS Defined
- CSS a simple mechanism for adding style (e.g.
fonts, colors, spacing) to Web documents. - Two Step process for using CSS
- Step 1 Create your styles
- Step 2 Apply your styles to your HTML document.
- Lets look at an example
30ltHTMLgt ltBODYgt ltSTYLE TYPE"text/css"gt lt!-- .HEADIN
G1 color blue font-size
64px .HEADING2 color gray font-size
22px --gt lt/STYLEgt ltSPAN CLASS"HEADING1"gtResume
Posting Servicelt/SPANgt ltPgt ltSPAN
CLASS"HEADING2"gtProvided by hotcomputerjobs.comlt/
SPANgt lt/BODYgt lt/HTMLgt
First, you create your styles Within a ltSTYLEgt
tag.
Then, you apply your styles By using the SPAN tag.
31Defining Styles
- Each Style has a name, and a set of properties.
- For example, the heading1 tag is set to blue, 64
pixels big - .HEADING1
- color blue
- font-size 64px
-
- Lots of properties exist color, font-size,
text-align, font-family, etc.
32Applying Styles
- Once you have created your styles, you apply a
style to your text via the SPAN tag. - For example, to apply the heading1 style
- ltSPAN CLASS"HEADING1"gtResume Posting
Servicelt/SPANgt
33SubmitResume.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,
lets view it in JCreator.
341.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("bgColo
r") - bgColor replaceIfMissing(bgColor, "WHITE")
352. Make the Style Sheet
- Based on the form parameters, we create an
appropriate stylesheet via the makeStyleSheet()
method - String styleSheet
- "ltSTYLE TYPE\"text/css\"gt\n"
- "lt!--\n"
- ".HEADING1 font-size " heading1Size
"px\n" - " font-weight bold\n"
- " font-family " headingFont
- "Arial, Helvetica,
sans-serif\n" - "\n"
- .
363. Output the HTML
- The showPreview() method outputs SPAN tags plus
resume data -
- "ltCENTERgt\n"
- "ltSPAN CLASS\"HEADING1\"gt" name
"lt/SPANgtltBRgt\n" - "ltSPAN CLASS\"HEADING2\"gt" title
"ltBRgt\n" - "ltA HREF\"mailto" email "\"gt" email
- "lt/Agtlt/SPANgt\n"
- "lt/CENTERgtltBRgtltBRgt\n"
-
37Filtering User Input
- Cross site scripting attack
- From watchguard.com
- Cross-site scripting attacks typically rely on
the fact that a Web designer has failed to
consider what actions the Web server or browser
may take if the text that users type into a form
(for example, requesting a name and address) is
not the expected alphanumeric characters, but is
one or more HTML tags, or a rogue script
(JavaScript, VBScript, ActiveX, PERL, etc.).
38For example
- Try submitting the following data to the
ThreeParams.java servlet - ltscriptgtalert('Test')lt/scriptgt
- Yikes! Thats not good. We need to filter out
this type of potentially malicious
HTML/Javascript code. - Complete details are available at CERT
- http//www.cert.org/advisories/CA-2000-02.html
39Lets look at this code ( any problems here?
- public class BadCodeServlet extends HttpServlet
- public void doGet(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException
- response.setContentType("text/html")
- PrintWriter out response.getWriter()
- String title "Code Sample"
- String docType
- "lt!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML
4.0 " - "Transitional//EN\"gt\n"
- out.println(docType
- "ltHTMLgt\n"
- "ltHEADgtltTITLEgt" title
"lt/TITLEgtlt/HEADgt\n" - "ltBODY BGCOLOR\"FDF5E6\"gt\n"
- "ltH1 ALIGN\"CENTER\"gt" title
"lt/H1gt\n" - "ltPREgt\n"
- getCode(request)
- "lt/PREgt\n"
- "Now, wasn't that an interesting
sample\n"
40ServletUtilities.java
- Fortunately, our text book includes a utility
method for filtering out malicious
HTML/Javascript code. - All contained in ServletUtilities.java
- Lets examine the code, and then check out a
sample safe servlet.
41- public static String filter(String input)
- StringBuffer filtered new
StringBuffer(input.length()) - char c
- for(int i0 iltinput.length() i)
- c input.charAt(i)
- if (c 'lt')
- filtered.append("lt")
- else if (c 'gt')
- filtered.append("gt")
- else if (c '"')
- filtered.append("quot")
- else if (c '')
- filtered.append("amp")
- else
- filtered.append(c)
-
-
- return(filtered.toString())
-
42- Lets run this example from the web
- Lets look at the code
43Summary
- When a user submits a browser request to a web
server, it sends two categories of data - Form Data
- HTTP Request Header Data
- The HttpServletRequest object contains three main
methods for extracting form data - getParameter()
- getParameterValues()
- getParameterNames()
- Filter user input to prevent cross-site scripting
attacks.