Title: Servlets and HTML Form Data
1Servlets and HTML Form Data
Vijayan Sugumaran Department of DIS Oakland
University Rochester, MI 48309
Parts of this presentation was provided by
www.coreservlets.com
2Generating HTML
- Set the Content-Type header
- Use response.setContentType
- Output HTML
- Be sure to include the DOCTYPE
- Use an HTML validation service
- http//validator.w3.org/
- http//www.htmlhelp.com/tools/validator/
- If your servlets are behind a firewall, you can
run them, save the HTML output, and use a file
upload form to validate.
3A Servlet That Generates HTML
- public class HelloWWW extends HttpServlet
- public void doGet(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException
- response.setContentType("text/html")
- PrintWriter out response.getWriter()
- String docType
- "lt!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML
4.0 " - "Transitional//EN\"gt\n"
- out.println(docType
- "ltHTMLgt\n"
- "ltHEADgtltTITLEgtHello
WWWlt/TITLEgtlt/HEADgt\n" - "ltBODYgt\n"
- "ltH1gtHello WWWlt/H1gt\n"
- "lt/BODYgtlt/HTMLgt")
-
4The Servlet Life Cycle
- init
- Executed once when the servlet is first loaded.
Not called for each request. - service
- Called in a new thread by server for each
request. Dispatches to doGet, doPost, etc. Do
not override this method! - doGet, doPost
- Handles GET, POST, etc. requests.
- Override these to provide desired behavior.
- destroy
- Called when server deletes servlet instance. Not
called after each request.
5Initializing Servlets
- Common in real-life servlets
- E.g., initializing database connection pools.
- Use ServletConfig.getInitParameter to read
initialization parameters - Set init parameters in web.xml (ver 2.2/2.3)
- /WEB-INF/web.xml
- Many servers have custom interfaces to create
web.xml - It is common to use init even when you dont
read init parameters - See modification date example in Core Servlets
and JavaServer Pages Chapter 2
6A Servlet That Uses Initialization Parameters
- public class ShowMessage extends HttpServlet
- private String message
- private String defaultMessage "No message."
- private int repeats 1
-
- public void init() throws ServletException
- ServletConfig config getServletConfig()
- message config.getInitParameter("message")
- if (message null)
- message defaultMessage
-
- try
- String repeatString
- config.getInitParameter("repeats")
- repeats Integer.parseInt(repeatString)
- catch(NumberFormatException nfe)
-
7ShowMessage Servlet (Continued)
- public void doGet(HttpServletRequest request,
- HttpServletResponse response)
- throws ServletException, IOException
- response.setContentType("text/html")
- PrintWriter out response.getWriter()
- String title "The ShowMessage Servlet"
- out.println(ServletUtilities.headWithTitle(t
itle) - "ltBODY BGCOLOR\"FDF5E6\"gt\n"
- "ltH1 ALIGNCENTERgt" title
"lt/H1gt") - for(int i0 iltrepeats i)
- out.println(message "ltBRgt")
-
- out.println("lt/BODYgtlt/HTMLgt")
-
-
8Setting Init Parameters
- ...\WEB-INF\web.xml
- tomcat_install_dir\webapps\examples\WEB-INF\web.xm
l - ltweb-appgt
- ltservletgt
- ltservlet-namegtShowMsglt/servlet-namegt
- ltservlet-classgtShowMessagelt/servlet-classgt
- ltinit-paramgt
- ltparam-namegtmessagelt/param-namegt
- ltparam-valuegtShibbolethlt/param-valuegt
- lt/init-paramgt
- ltinit-paramgt
- ltparam-namegtrepeatslt/param-namegt
- ltparam-valuegt5lt/param-valuegt
- lt/init-paramgt
- lt/servletgt
- lt/web-appgt
9ShowMessage Result
10Debugging Servlets
- Use print statements run server on desktop
- Integrated debugger in IDE
- Look at the HTML source
- Return error pages to the client
- Plan ahead for missing or malformed data
- Use the log file
- log("message") or log("message", Throwable)
- Look at the request data separately.
- See EchoServer at www.coreservlets.com
- Look at the response data separately
- See WebClient at www.coreservlets.com
- Stop and restart the server
11Handling the Client Request Form Data
12The Role of Form Data
- Example URL at online travel agent
- http//host/path?userMartyHalloriginbwidestl
ax - Names come from HTML author values usually come
from end user - Parsing form (query) data in traditional CGI
- Read the data one way (QUERY_STRING) for GET
requests, another way (standard input) for POST
requests - Chop pairs at ampersands, then separate parameter
names (left of the equal signs) from parameter
values (right of the equal signs) - URL decode values (e.g., "7E" becomes "")
- Need special cases for omitted values(param1val1
param2param3val3) and repeated parameters
(param1val1param2val2param1val3)
13Creating Form Data HTML Forms
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - ltHTMLgt
- ltHEADgtltTITLEgtA Sample Form Using
GETlt/TITLEgtlt/HEADgt - ltBODY BGCOLOR"FDF5E6"gt
- ltH2 ALIGN"CENTER"gtA Sample Form Using GETlt/H2gt
- ltFORM ACTION"http//localhost8088/SomeProgram"gt
- ltCENTERgt
- First name
- ltINPUT TYPE"TEXT" NAME"firstName"
VALUE"Joe"gtltBRgt - Last name
- ltINPUT TYPE"TEXT" NAME"lastName"
VALUE"Hacker"gtltPgt - ltINPUT TYPE"SUBMIT"gt lt!-- Press this to submit
form --gt - lt/CENTERgt
- lt/FORMgt
- lt/BODYgtlt/HTMLgt
14Aside Installing HTML Files
- Tomcat
- install_dir\webapps\examples\Form.html or
- install_dir\webapps\examples\SomeDir\Form.html
- JRun
- install_dir\servers\default\default-app\Form.html
or - install_dir\servers\default\default-app\SomeDir\Fo
rm.html - URL
- http//localhost/Form.html or
- http//localhost/SomeDir/Form.html
15HTML Form Initial Result
16HTML Form Submission Result(Data Sent to
EchoServer)
17Sending POST Data
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - ltHTMLgt
- ltHEADgtltTITLEgtA Sample Form Using
POSTlt/TITLEgtlt/HEADgt - ltBODY BGCOLOR"FDF5E6"gt
- ltH2 ALIGN"CENTER"gtA Sample Form Using POSTlt/H2gt
- ltFORM ACTION"http//localhost8088/SomeProgram"
- METHOD"POST"gt
- ltCENTERgt
- First name
- ltINPUT TYPE"TEXT" NAME"firstName"
VALUE"Joe"gtltBRgt - Last name
- ltINPUT TYPE"TEXT" NAME"lastName"
VALUE"Hacker"gtltPgt - ltINPUT TYPE"SUBMIT"gt
- lt/CENTERgt
- lt/FORMgt
- lt/BODYgtlt/HTMLgt
18Sending POST Data
19Reading Form Data In Servlets
- request.getParameter("name")
- Returns URL-decoded value of first occurrence of
name in query string - Works identically for GET and POST requests
- Returns null if no such parameter is in query
- request.getParameterValues("name")
- Returns an array of the URL-decoded values of all
occurrences of name in query string - Returns a one-element array if param not repeated
- Returns null if no such parameter is in query
- request.getParameterNames()
- Returns Enumeration of request params
20An HTML Form With Three Parameters
- ltFORM ACTION"/servlet/coreservlets.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 - ltCENTERgtltINPUT TYPE"SUBMIT"gtlt/CENTERgt
- lt/FORMgt
21Reading the Three Parameters
- 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" - out.println(ServletUtilities.headWithTitle(tit
le) - "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")
22Reading Three ParametersResult
23Reading All Parameters
- 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(tit
le) - "ltBODY BGCOLOR\"FDF5E6\"gt\n"
- "ltH1 ALIGNCENTERgt" title
"lt/H1gt\n" - "ltTABLE BORDER1 ALIGNCENTERgt\n"
- "ltTR BGCOLOR\"FFAD00\"gt\n"
- "ltTHgtParameter NameltTHgtParameter
Value(s)")
24Reading All Parameters (cont)
- Enumeration paramNames request.getParameterN
ames() - while(paramNames.hasMoreElements())
- String paramName (String)paramNames.nextEl
ement() - 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)
25Reading All Parameters (cont)
- else
- out.println("ltULgt")
- for(int i0 iltparamValues.length i)
- out.println("ltLIgt" paramValuesi)
-
- out.println("lt/ULgt")
-
-
- out.println("lt/TABLEgt\nlt/BODYgtlt/HTMLgt")
-
- public void doPost(HttpServletRequest request,
- HttpServletResponse
response) - throws ServletException, IOException
- doGet(request, response)
-
26Result of ShowParameters Servlet
- Note that order of parameters in Enumeration does
not match order they appeared in Web page
27Summary
- Query data comes from HTML forms as URL-encoded
name/value pairs - Servlets read data by calling request.getParameter
("name") - Results in value as entered into form, not as
sent over network. I.e. not URL-encoded. - Always check for missing or malformed data
- Special case query data that contains special
HTML characters - Need to be filtered if query data will be placed
into resultant HTML page