SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
© 2010 Marty Hall
Handling the ClientHandling the Client
Request: Form Dataq
Originals of Slides and Source Code for Examples:
http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.3
© 2010 Marty Hall
For live Java EE training, please see training courses
at http://courses.coreservlets.com/.at http://courses.coreservlets.com/.
Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo,
Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT),
Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g
Hibernate/JPA, and customized combinations of topics.
Taught by the author of Core Servlets and JSP, More
Servlets and JSP and this tutorial Available at public
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.
Servlets and JSP, and this tutorial. Available at public
venues, or customized versions can be held on-site at your
organization. Contact hall@coreservlets.com for details.
Agenda
• The role of form data
• Creating and submitting HTML forms
• Reading individual request parametersg q p
• Reading the entire set of request parameters
• Handling missing and malformed dataHandling missing and malformed data
• Dealing with incomplete form submissions
• Filtering special characters out of the• Filtering special characters out of the
request parameters
5
© 2010 Marty Hall
Form Basics
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.6
The Role of Form Data
• Example URL at online travel agent
– http://host/path?user=Marty+Hall&origin=bwi&dest=lax
– Names come from HTML author; values from end user
Parsing form (query) data in traditional CGI• Parsing form (query) data in traditional CGI
– Read the data one way (QUERY_STRING) for GET
requests, another way (standard input) for POST requestsq , y ( p ) OS q
– Chop pairs at ampersands, then separate parameter names
(left of the =) from parameter values (right of the =)
URL d d l ( "%7E" b " ")– URL decode values (e.g., "%7E" becomes "~")
• Greatly simplified in servlets
Use request getParameter in all cases– Use request.getParameter in all cases.
– Gives URL-decoded result
7
Creating Form Data:
HTML FormsHTML Forms
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using GET</H2>
You normally use
a relative URL for the
ACTION. This URL is just
for testing because I am
<FORM ACTION="http://localhost:8088/SomeProgram">
<CENTER>
First name:
running a test server on
port 8088 that echoes the
data it receives.
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="J. Random"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P>
<INPUT TYPE="SUBMIT"> <!-- Press this to submit form -->
</CENTER>
</FORM>
</BODY></HTML></BODY></HTML>
• See CSAJSP/2 Ch. 19 for details on forms8
Aside: Installing HTML Files
• HTML files do not go in src
– They go in WebContent
• When deployed, that becomes the top-level Web
application directorypp y
• In contrast, code under src gets deployed to the
WEB-INF/classes folder of the Web app directory
• Example• Example
– Eclipse project name: forms
– Files
• WebContent/test1.html
• WebContent/someDir/test2.html
URLs– URLs
• http://localhost/forms/test1.html
• http://localhost/forms/someDir/test2.html9
GET Form: Initial Result
10
GET Form: Submission Result
(Data Sent to EchoServer)(Data Sent to EchoServer)
11
Sending POST Data
<!DOCTYPE ... >
<HTML>
<HEAD><TITLE>A Sample Form Using POST</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<H2 ALIGN="CENTER">A Sample Form Using POST</H2>
<FORM ACTION="http://localhost:8088/SomeProgram"
METHOD="POST">
<CENTER>
The default method is GET. So, if a form says METHOD="GET" or it
has no METHOD at all, GET is used.
First name:
<INPUT TYPE="TEXT" NAME="firstName" VALUE="J. Random"><BR>
Last name:
<INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P><INPUT TYPE= TEXT NAME= lastName VALUE= Hacker ><P>
<INPUT TYPE="SUBMIT">
</CENTER>
</FORM>
</BODY></HTML>
12
POST Form: Initial Result
13
POST Form: Submission Result
(Data Sent to EchoServer)(Data Sent to EchoServer)
14
HTML 4 vs. XHTML Syntax
• HTML 4
S d t ti l– Some end tags optional
– Tag names and attribute names are case insensitive
• XHTML
– End tags always required
• If no body content, can use collapsed form like <br/>
– Tag names and attribute names must be in lower case
• HTML 5 DOCTYPE
– Most people who use the HTML 5 DOCTYPE do so as a
convenience, and follow XHTML syntax in their pages.co ve e ce, a d o ow sy a e pages.
• Examples
– HTML 4
• <INPUT TYPE="TEXT" NAME="Blah"><BR>• <INPUT TYPE= TEXT NAME= Blah ><BR>
– XHTML
• <input type="text" name="Blah"/><br/>
15
© 2010 Marty Hall
Reading Form Data
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.16
Reading Form Data In Servlets
• request.getParameter("name")
R t URL d d d l f fi t f– 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 data
• request.getParameterValues("name")
– Returns an array of the URL-decoded values of all– 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
R t ll if h t i i– Returns null if no such parameter is in query
• request.getParameterNames() or
request.getParameterMap()q g p()
– Returns Enumeration or Map of request params
– Usually reserved for debugging
17
An HTML Form With Three
ParametersParameters
<FORM ACTION="three-params">
First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>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>
18
• Project name is “forms”
• Form installed in WebContent/three-params-form.html
Reading the Three Parameters
@WebServlet("three-params")
public class ThreeParams extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
…
out.println(docType +
"<HTML>n" +
"<HEAD><TITLE>"+title + "</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1 ALIGN="CENTER">" + title + "</H1>n" +
"<UL>n" +
" <LI><B>param1</B>: "
+ request.getParameter("param1") + "n" +q g p
" <LI><B>param2</B>: "
+ request.getParameter("param2") + "n" +
" <LI><B>param3</B>: "
+ request.getParameter("param3") + "n" +q g ( p )
"</UL>n" +
"</BODY></HTML>");
}
}19
Reading Three Parameters:
ResultResult
20
Reading All Parameters
@WebServlet("show-params")
public class ShowParameters extends HttpServlet {p p {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
( / )response.setContentType("text/html");
PrintWriter out = response.getWriter();
String docType =
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +<!DOCTYPE HTML PUBLIC  //W3C//DTD HTML 4.0 +
"Transitional//EN">n";
String title = "Reading All Request Parameters";
out.println(docType +
"<HTML>n" +
"<HEAD><TITLE>"+title + "</TITLE></HEAD>n"+
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1 ALIGN=CENTER>" + title + "</H1>n" +<H1 ALIGN=CENTER> + title + </H1>n +
"<TABLE BORDER=1 ALIGN=CENTER>n" +
"<TR BGCOLOR="#FFAD00">n" +
"<TH>Parameter Name<TH>Parameter Value(s)");21
Reading All Parameters
(Continued)(Continued)
Enumeration<String> paramNames =
request.getParameterNames();
while(paramNames.hasMoreElements()) {
String paramName = (String)paramNames.nextElement();
out.print("<TR><TD>" + paramName + "n<TD>");
String[] paramValues =
req est getParameterVal es(paramName)request.getParameterValues(paramName);
if (paramValues.length == 1) {
String paramValue = paramValues[0];
if (paramValue.length() == 0)
out println("<I>No Value</I>");out.println( <I>No Value</I> );
else
out.println(paramValue);
} else {
out.println("<UL>");out.println( <UL> );
for(int i=0; i<paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");p
}
}
out.println("</TABLE>n</BODY></HTML>");
}22
Reading All Parameters
(Continued)(Continued)
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException IOException {throws ServletException, IOException {
doGet(request, response);
}
}}
23
Reading All Parameters
(Sample Form)(Sample Form)
24
Reading All Parameters (Result)
25
© 2010 Marty Hall
Handling Missing andHandling Missing and
Malformed Data
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.26
Checking for Missing and
Malformed DataMalformed Data
• Missing
– Field missing in form
• getParameter returns null
– Field blank when form submitted– Field blank when form submitted
• getParameter returns an empty string (or possibly a string
with whitespace in it)
M t h k f ll b f h ki f t t i– Must check for null before checking for empty string
String param = request.getParameter("someName");
if ((param == null) || (param.trim().equals(""))) {
doSomethingForMissingValues( );doSomethingForMissingValues(...);
} else {
doSomethingWithParameter(param);
}
• Malformed
– Value is a nonempty string in the wrong format27
Checking for Missing and
Malformed DataMalformed Data
• Principles
– Assume user data could be missing or in wrong format
– Users should never see Java error messages
• Only error messages you create aimed at end users• Only error messages you create, aimed at end users
28
Handling Missing and
Malformed DataMalformed Data
• Use default values
Replace missing values with application specific standard values– Replace missing values with application-specific standard values
– See following example
• Redisplay the form
Show the form again with missing values flagged– Show the form again, with missing values flagged
– Previously-entered values should be preserved
– Best option for implementing this: use framework like JSF or Struts
• Covered in later tutorialsCovered in later tutorials
– Four options to implement this directly
• Have the same servlet present the form, process the data, and
present the results.
S b k f l– See book for example
• Have one servlet present the form; have a second servlet
process the data and present the results.
• Have a JSP page “manually” present the form; have a servlet or
JSP th d t d t th ltJSP page process the data and present the results.
• Have a JSP page present the form, automatically filling in the
fields with values obtained from a data object. Have a servlet or
JSP page process the data and present the results.29
Example of Using Default
Values: A Résumé-Posting SiteValues: A Résumé-Posting Site
30
Résumé-Posting Site: Input
Form and Good Data ResultsForm and Good Data Results
31
Résumé-Posting Site:
Servlet CodeServlet Code
headingFont =
replaceIfMissingOrDefault(headingFont "");replaceIfMissingOrDefault(headingFont, );
int headingSize =
getSize(request.getParameter("headingSize"),
32);32);
String bodyFont =
request.getParameter("bodyFont");
bodyFont =bodyFont
replaceIfMissingOrDefault(bodyFont, "");
int bodySize =
getSize(request.getParameter("bodySize"), 18);getS e( equest.get a a ete ( bodyS e ), 8);
String fgColor = request.getParameter("fgColor");
fgColor =
replaceIfMissing(fgColor, "BLACK");p g( g , );
String bgColor = request.getParameter("bgColor");
32
Résumé-Posting Site:
Servlet Code (Continued)Servlet Code (Continued)
private String replaceIfMissing(String orig,private String replaceIfMissing(String orig,
String replacement) {
if ((orig == null) || (orig.trim().equals(""))) {
return(replacement);( p )
} else {
return(orig);
}
}
33
Résumé-Posting Site:
Result for Incomplete DataResult for Incomplete Data
34
Filtering Strings for HTML-
Specific Characters (Code)Specific Characters (Code)
public class ServletUtilities {
public static String filter(String input) {p g ( g p ) {
if (!hasSpecialChars(input)) {
return(input);
}
StringBuilder filtered =StringBuilder filtered =
new StringBuilder(input.length());
char c;
for(int i=0; i<input.length(); i++) {
c = input.charAt(i);
switch(c) {
case '<': filtered.append("&lt;"); break;
case '>': filtered append("&gt;"); break;case > : filtered.append( &gt; ); break;
case '"': filtered.append("&quot;"); break;
case '&': filtered.append("&amp;"); break;
default: filtered.append(c);
}
}
return(filtered.toString());
} …35
A Servlet that Displays Code
Samples: No FilteringSamples: No Filtering
@WebServlet("/code-preview-bad")
public class CodePreviewBad extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
…
out.println(docType +
"<HTML>n" +
"<HEAD><TITLE>"+title+"</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<H1 ALIGN="CENTER">" + title + "</H1>n"+
"<PRE>n" +
getCode(request) +
"</PRE>n" +
"Now, wasn't that an interesting samplen" +
"of code?n" +
"</BODY></HTML>");
}}
protected String getCode(HttpServletRequest request) {
return(request.getParameter("code"));
}
}36
A Servlet that Displays Code
Samples: No Special CharsSamples: No Special Chars
37
A Servlet that Displays Code
Samples: Special CharsSamples: Special Chars
38
A Servlet that Displays Code
Samples: FilteringSamples: Filtering
@WebServlet("/code-preview-good")
public class CodePreviewGood extends CodePreviewBad {public class CodePreviewGood extends CodePreviewBad {
protected String getCode(HttpServletRequest request) {
return
(ServletUtilities.filter(super.getCode(request)));
}
}
39
Fixed Servlet that Displays
Code Samples: Special CharsCode Samples: Special Chars
40
© 2010 Marty Hall
Advanced Topics
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.41
Tags for Form Aesthetics
• label
– If you use the label tag for prompts associated with fields,
clicking on the label transfers focus to the input field
– You can either use the "for" attribute or enclose the field– You can either use the for attribute or enclose the field
within the label
• <label for="fname">First name:</label>
<input type="text" name="userFirstName" id="fname"/><input type= text name= userFirstName id= fname />
• <label>First name:
<input type="text" name="userFirstName"
</label></label>
• fieldset and legend
– Grouping all or part of a form inside fieldset drawsGrouping all or part of a form inside fieldset draws
attention to it and separates it from the rest of the page
– Using style sheets for the legend is particularly useful42
Tags for Form Aesthetics:
ExampleExample
• HTML
<fieldset>
<legend>ajax:updateField</legend>
<form ...>
<label for="f">Enter temperature in Fahrenheit:</label>
<input type="text" id="f"/>
<input type="button" id="convertButton" value="Convert"/>
<hr width="500" align="left"/>
<label for="c">Temperature in Celsius:</label>
<input type="text" id="c"/>
<l b l f "k">T t i K l i </l b l><label for="k">Temperature in Kelvin:</label>
<input type="text" id="k"/>
</form>
</fieldset>
CSS• CSS
legend {
font-weight: bold;
color: black;
background-color: white;
border: 1px solid #cccccc;
padding: 4px 2px;
}43
Handling Input in Multiple
LanguagesLanguages
• Use server's default character set
String firstName =
request.getParameter("firstName");
C t f E li h (L ti 1) t J• Convert from English (Latin-1) to Japanese
String firstNameWrongEncoding =
request getParameter("firstName");request.getParameter( firstName );
String firstName =
new String(firstNameWrongEncoding.getBytes(),
"Shift JIS")"Shift_JIS");
• Accept either English or Japanese
request setCharacterEncoding("JISAutoDetect");request.setCharacterEncoding( JISAutoDetect );
String firstName =
request.getParameter("firstName");
44
Reading Raw Form Data and
Parsing Uploaded FilesParsing Uploaded Files
• Raw data
– request.getReader
– request.getInputStream
• Data no longer available via getParameter after this• Data no longer available via getParameter after this
• Parsing uploaded files
– HTML has a way of submitting entire filesy g
• <INPUT TYPE="FILE"…>
– See Section 19.7 of 2nd Edition of Core Servlets and JSP.
Servlet/JSP APIs have no builtin way to parse files– Servlet/JSP APIs have no builtin way to parse files
– Popular third-party library available from the
Apache/Jakarta “Commons” library
• http://jakarta.apache.org/commons/fileupload/
45
More Advanced Topics
(See book for details/examples)(See book for details/examples)
• Automatically filling in a data object with request
parameter al esparameter values
– Use a JavaBean (Java object with methods named getBlah and
setBlah) to store incoming data
– Request param named blah passed to appropriate setBlah method.
Automatic type conversion. Default values used for errors.
• Redisplaying the input form when parameters arep y g p p
missing or malformed
– The same servlet presents the form, processes the data, and presents
the results. JSF provides better solution – see later tutorials!p
• The servlet first looks for incoming request data: if it finds
none, it presents a blank form. If the servlet finds partial
request data, it extracts the partial data, puts it back intoq p p
the form, and marks the other fields as missing. If the
servlet finds the full complement of required data, it
processes the request and displays the results.46
Summary
• Make a form: <form …> … </form>
– Relative URL for “action”. Textfields need “name”.
Should always have submit button.
• Read data: request getParameter("name")• Read data: request.getParameter( name )
– Results in value as entered into form, not necessarily as
sent over network. I.e., not URL-encoded.
• Check for missing or malformed data
– Missing: null or empty string
– Special case: query data that contains special HTML
characters
• Need to be filtered if query data will be placed intoNeed to be filtered if query data will be placed into
resultant HTML page
47
© 2010 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6.
Developed and taught by well-known author and developer. At public venues or onsite at your location.48

Mais conteúdo relacionado

Mais procurados

Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaAleksander Pohl
 
Solr Query Parsing
Solr Query ParsingSolr Query Parsing
Solr Query ParsingErik Hatcher
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQLRaji Ghawi
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTTkevinvw
 
Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2Gheyath M. Othman
 
Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...
Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...
Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...ruyalarcon
 
Get the most out of Solr search with PHP
Get the most out of Solr search with PHPGet the most out of Solr search with PHP
Get the most out of Solr search with PHPPaul Borgermans
 
An Introduction to the Jena API
An Introduction to the Jena APIAn Introduction to the Jena API
An Introduction to the Jena APICraig Trim
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionseyelliando dias
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes WorkshopErik Hatcher
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conferenceErik Hatcher
 
The Functional Web
The Functional WebThe Functional Web
The Functional WebRyan Riley
 

Mais procurados (20)

working with PHP & DB's
working with PHP & DB'sworking with PHP & DB's
working with PHP & DB's
 
REST dojo Comet
REST dojo CometREST dojo Comet
REST dojo Comet
 
Apache Solr Workshop
Apache Solr WorkshopApache Solr Workshop
Apache Solr Workshop
 
Jena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for JavaJena – A Semantic Web Framework for Java
Jena – A Semantic Web Framework for Java
 
Solr Query Parsing
Solr Query ParsingSolr Query Parsing
Solr Query Parsing
 
Java and SPARQL
Java and SPARQLJava and SPARQL
Java and SPARQL
 
Python & Django TTT
Python & Django TTTPython & Django TTT
Python & Django TTT
 
JSON in Solr: from top to bottom
JSON in Solr: from top to bottomJSON in Solr: from top to bottom
JSON in Solr: from top to bottom
 
Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2Web Development Course: PHP lecture 2
Web Development Course: PHP lecture 2
 
Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...
Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...
Fulfilling the Hypermedia Constraint via HTTP OPTIONS, The HTTP Vocabulary In...
 
Get the most out of Solr search with PHP
Get the most out of Solr search with PHPGet the most out of Solr search with PHP
Get the most out of Solr search with PHP
 
Web services tutorial
Web services tutorialWeb services tutorial
Web services tutorial
 
An Introduction to the Jena API
An Introduction to the Jena APIAn Introduction to the Jena API
An Introduction to the Jena API
 
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey IntroductionseyCwinters Intro To Rest And JerREST and Jersey Introductionsey
Cwinters Intro To Rest And JerREST and Jersey Introductionsey
 
Solr Recipes Workshop
Solr Recipes WorkshopSolr Recipes Workshop
Solr Recipes Workshop
 
Jena framework
Jena frameworkJena framework
Jena framework
 
Solr Black Belt Pre-conference
Solr Black Belt Pre-conferenceSolr Black Belt Pre-conference
Solr Black Belt Pre-conference
 
The Functional Web
The Functional WebThe Functional Web
The Functional Web
 
Apache Solr
Apache SolrApache Solr
Apache Solr
 
01 html-introduction
01 html-introduction01 html-introduction
01 html-introduction
 

Destaque

02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basicssnopteck
 
07 cookies
07 cookies07 cookies
07 cookiessnopteck
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPsKind of Digital
 
11 page-directive
11 page-directive11 page-directive
11 page-directivesnopteck
 
13 java beans
13 java beans13 java beans
13 java beanssnopteck
 
04 request-headers
04 request-headers04 request-headers
04 request-headerssnopteck
 

Destaque (7)

02 servlet-basics
02 servlet-basics02 servlet-basics
02 servlet-basics
 
07 cookies
07 cookies07 cookies
07 cookies
 
Digital Engagement for CSPs
Digital Engagement for CSPsDigital Engagement for CSPs
Digital Engagement for CSPs
 
10 jdbc
10 jdbc10 jdbc
10 jdbc
 
11 page-directive
11 page-directive11 page-directive
11 page-directive
 
13 java beans
13 java beans13 java beans
13 java beans
 
04 request-headers
04 request-headers04 request-headers
04 request-headers
 

Semelhante a Handling form data in servlets

05 status-codes
05 status-codes05 status-codes
05 status-codessnopteck
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags AdvancedAkramWaseem
 
Ajax Basics 2
Ajax Basics 2Ajax Basics 2
Ajax Basics 2bhuvanann
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaKatrien Verbert
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSCarol McDonald
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 
15 expression-language
15 expression-language15 expression-language
15 expression-languagesnopteck
 
Adriano Di Luzio - Davvy - PyconSEI Talk
Adriano Di Luzio - Davvy - PyconSEI TalkAdriano Di Luzio - Davvy - PyconSEI Talk
Adriano Di Luzio - Davvy - PyconSEI Talkaldur999
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application FrameworkSimon Willison
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API07.pallav
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.pptWalaSidhom1
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceMaarten Balliauw
 
Java Technology
Java TechnologyJava Technology
Java Technologyifnu bima
 

Semelhante a Handling form data in servlets (20)

05 status-codes
05 status-codes05 status-codes
05 status-codes
 
Android networking-2
Android networking-2Android networking-2
Android networking-2
 
Ajax basics
Ajax basicsAjax basics
Ajax basics
 
Ajax Tags Advanced
Ajax Tags AdvancedAjax Tags Advanced
Ajax Tags Advanced
 
Ajax Basics 2
Ajax Basics 2Ajax Basics 2
Ajax Basics 2
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
Rest
RestRest
Rest
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
WebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPediaWebTech Tutorial Querying DBPedia
WebTech Tutorial Querying DBPedia
 
Jersey
JerseyJersey
Jersey
 
RESTful Web Services with JAX-RS
RESTful Web Services with JAX-RSRESTful Web Services with JAX-RS
RESTful Web Services with JAX-RS
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 
15 expression-language
15 expression-language15 expression-language
15 expression-language
 
Adriano Di Luzio - Davvy - PyconSEI Talk
Adriano Di Luzio - Davvy - PyconSEI TalkAdriano Di Luzio - Davvy - PyconSEI Talk
Adriano Di Luzio - Davvy - PyconSEI Talk
 
The Django Web Application Framework
The Django Web Application FrameworkThe Django Web Application Framework
The Django Web Application Framework
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
nodejs_at_a_glance.ppt
nodejs_at_a_glance.pptnodejs_at_a_glance.ppt
nodejs_at_a_glance.ppt
 
Building a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to SpaceBuilding a friendly .NET SDK to connect to Space
Building a friendly .NET SDK to connect to Space
 
Java Technology
Java TechnologyJava Technology
Java Technology
 

Mais de snopteck

08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-trackingsnopteck
 
06 response-headers
06 response-headers06 response-headers
06 response-headerssnopteck
 
01 web-apps
01 web-apps01 web-apps
01 web-appssnopteck
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setupsnopteck
 

Mais de snopteck (7)

10 jdbc
10 jdbc10 jdbc
10 jdbc
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
14 mvc
14 mvc14 mvc
14 mvc
 
08 session-tracking
08 session-tracking08 session-tracking
08 session-tracking
 
06 response-headers
06 response-headers06 response-headers
06 response-headers
 
01 web-apps
01 web-apps01 web-apps
01 web-apps
 
01 overview-and-setup
01 overview-and-setup01 overview-and-setup
01 overview-and-setup
 

Último

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 

Último (20)

The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 

Handling form data in servlets

  • 1. © 2010 Marty Hall Handling the ClientHandling the Client Request: Form Dataq Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.3 © 2010 Marty Hall For live Java EE training, please see training courses at http://courses.coreservlets.com/.at http://courses.coreservlets.com/. Servlets, JSP, Struts, JSF 1.x, JSF 2.0, Ajax (with jQuery, Dojo, Prototype, Ext-JS, Google Closure, etc.), GWT 2.0 (with GXT), Java 5, Java 6, SOAP-based and RESTful Web Services, Spring,g Hibernate/JPA, and customized combinations of topics. Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial Available at public Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location. Servlets and JSP, and this tutorial. Available at public venues, or customized versions can be held on-site at your organization. Contact hall@coreservlets.com for details.
  • 2. Agenda • The role of form data • Creating and submitting HTML forms • Reading individual request parametersg q p • Reading the entire set of request parameters • Handling missing and malformed dataHandling missing and malformed data • Dealing with incomplete form submissions • Filtering special characters out of the• Filtering special characters out of the request parameters 5 © 2010 Marty Hall Form Basics Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.6
  • 3. The Role of Form Data • Example URL at online travel agent – http://host/path?user=Marty+Hall&origin=bwi&dest=lax – Names come from HTML author; values from end user Parsing form (query) data in traditional CGI• Parsing form (query) data in traditional CGI – Read the data one way (QUERY_STRING) for GET requests, another way (standard input) for POST requestsq , y ( p ) OS q – Chop pairs at ampersands, then separate parameter names (left of the =) from parameter values (right of the =) URL d d l ( "%7E" b " ")– URL decode values (e.g., "%7E" becomes "~") • Greatly simplified in servlets Use request getParameter in all cases– Use request.getParameter in all cases. – Gives URL-decoded result 7 Creating Form Data: HTML FormsHTML Forms <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD><TITLE>A Sample Form Using GET</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <H2 ALIGN="CENTER">A Sample Form Using GET</H2> You normally use a relative URL for the ACTION. This URL is just for testing because I am <FORM ACTION="http://localhost:8088/SomeProgram"> <CENTER> First name: running a test server on port 8088 that echoes the data it receives. First name: <INPUT TYPE="TEXT" NAME="firstName" VALUE="J. Random"><BR> Last name: <INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P> <INPUT TYPE="SUBMIT"> <!-- Press this to submit form --> </CENTER> </FORM> </BODY></HTML></BODY></HTML> • See CSAJSP/2 Ch. 19 for details on forms8
  • 4. Aside: Installing HTML Files • HTML files do not go in src – They go in WebContent • When deployed, that becomes the top-level Web application directorypp y • In contrast, code under src gets deployed to the WEB-INF/classes folder of the Web app directory • Example• Example – Eclipse project name: forms – Files • WebContent/test1.html • WebContent/someDir/test2.html URLs– URLs • http://localhost/forms/test1.html • http://localhost/forms/someDir/test2.html9 GET Form: Initial Result 10
  • 5. GET Form: Submission Result (Data Sent to EchoServer)(Data Sent to EchoServer) 11 Sending POST Data <!DOCTYPE ... > <HTML> <HEAD><TITLE>A Sample Form Using POST</TITLE></HEAD> <BODY BGCOLOR="#FDF5E6"> <H2 ALIGN="CENTER">A Sample Form Using POST</H2> <FORM ACTION="http://localhost:8088/SomeProgram" METHOD="POST"> <CENTER> The default method is GET. So, if a form says METHOD="GET" or it has no METHOD at all, GET is used. First name: <INPUT TYPE="TEXT" NAME="firstName" VALUE="J. Random"><BR> Last name: <INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P><INPUT TYPE= TEXT NAME= lastName VALUE= Hacker ><P> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY></HTML> 12
  • 6. POST Form: Initial Result 13 POST Form: Submission Result (Data Sent to EchoServer)(Data Sent to EchoServer) 14
  • 7. HTML 4 vs. XHTML Syntax • HTML 4 S d t ti l– Some end tags optional – Tag names and attribute names are case insensitive • XHTML – End tags always required • If no body content, can use collapsed form like <br/> – Tag names and attribute names must be in lower case • HTML 5 DOCTYPE – Most people who use the HTML 5 DOCTYPE do so as a convenience, and follow XHTML syntax in their pages.co ve e ce, a d o ow sy a e pages. • Examples – HTML 4 • <INPUT TYPE="TEXT" NAME="Blah"><BR>• <INPUT TYPE= TEXT NAME= Blah ><BR> – XHTML • <input type="text" name="Blah"/><br/> 15 © 2010 Marty Hall Reading Form Data Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.16
  • 8. Reading Form Data In Servlets • request.getParameter("name") R t URL d d d l f fi t f– 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 data • request.getParameterValues("name") – Returns an array of the URL-decoded values of all– 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 R t ll if h t i i– Returns null if no such parameter is in query • request.getParameterNames() or request.getParameterMap()q g p() – Returns Enumeration or Map of request params – Usually reserved for debugging 17 An HTML Form With Three ParametersParameters <FORM ACTION="three-params"> First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR>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> 18 • Project name is “forms” • Form installed in WebContent/three-params-form.html
  • 9. Reading the Three Parameters @WebServlet("three-params") public class ThreeParams extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { … out.println(docType + "<HTML>n" + "<HEAD><TITLE>"+title + "</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<H1 ALIGN="CENTER">" + title + "</H1>n" + "<UL>n" + " <LI><B>param1</B>: " + request.getParameter("param1") + "n" +q g p " <LI><B>param2</B>: " + request.getParameter("param2") + "n" + " <LI><B>param3</B>: " + request.getParameter("param3") + "n" +q g ( p ) "</UL>n" + "</BODY></HTML>"); } }19 Reading Three Parameters: ResultResult 20
  • 10. Reading All Parameters @WebServlet("show-params") public class ShowParameters extends HttpServlet {p p { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ( / )response.setContentType("text/html"); PrintWriter out = response.getWriter(); String docType = "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 " +<!DOCTYPE HTML PUBLIC //W3C//DTD HTML 4.0 + "Transitional//EN">n"; String title = "Reading All Request Parameters"; out.println(docType + "<HTML>n" + "<HEAD><TITLE>"+title + "</TITLE></HEAD>n"+ "<BODY BGCOLOR="#FDF5E6">n" + "<H1 ALIGN=CENTER>" + title + "</H1>n" +<H1 ALIGN=CENTER> + title + </H1>n + "<TABLE BORDER=1 ALIGN=CENTER>n" + "<TR BGCOLOR="#FFAD00">n" + "<TH>Parameter Name<TH>Parameter Value(s)");21 Reading All Parameters (Continued)(Continued) Enumeration<String> paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print("<TR><TD>" + paramName + "n<TD>"); String[] paramValues = req est getParameterVal es(paramName)request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) out println("<I>No Value</I>");out.println( <I>No Value</I> ); else out.println(paramValue); } else { out.println("<UL>");out.println( <UL> ); for(int i=0; i<paramValues.length; i++) { out.println("<LI>" + paramValues[i]); } out.println("</UL>");p } } out.println("</TABLE>n</BODY></HTML>"); }22
  • 11. Reading All Parameters (Continued)(Continued) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException IOException {throws ServletException, IOException { doGet(request, response); } }} 23 Reading All Parameters (Sample Form)(Sample Form) 24
  • 12. Reading All Parameters (Result) 25 © 2010 Marty Hall Handling Missing andHandling Missing and Malformed Data Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.26
  • 13. Checking for Missing and Malformed DataMalformed Data • Missing – Field missing in form • getParameter returns null – Field blank when form submitted– Field blank when form submitted • getParameter returns an empty string (or possibly a string with whitespace in it) M t h k f ll b f h ki f t t i– Must check for null before checking for empty string String param = request.getParameter("someName"); if ((param == null) || (param.trim().equals(""))) { doSomethingForMissingValues( );doSomethingForMissingValues(...); } else { doSomethingWithParameter(param); } • Malformed – Value is a nonempty string in the wrong format27 Checking for Missing and Malformed DataMalformed Data • Principles – Assume user data could be missing or in wrong format – Users should never see Java error messages • Only error messages you create aimed at end users• Only error messages you create, aimed at end users 28
  • 14. Handling Missing and Malformed DataMalformed Data • Use default values Replace missing values with application specific standard values– Replace missing values with application-specific standard values – See following example • Redisplay the form Show the form again with missing values flagged– Show the form again, with missing values flagged – Previously-entered values should be preserved – Best option for implementing this: use framework like JSF or Struts • Covered in later tutorialsCovered in later tutorials – Four options to implement this directly • Have the same servlet present the form, process the data, and present the results. S b k f l– See book for example • Have one servlet present the form; have a second servlet process the data and present the results. • Have a JSP page “manually” present the form; have a servlet or JSP th d t d t th ltJSP page process the data and present the results. • Have a JSP page present the form, automatically filling in the fields with values obtained from a data object. Have a servlet or JSP page process the data and present the results.29 Example of Using Default Values: A Résumé-Posting SiteValues: A Résumé-Posting Site 30
  • 15. Résumé-Posting Site: Input Form and Good Data ResultsForm and Good Data Results 31 Résumé-Posting Site: Servlet CodeServlet Code headingFont = replaceIfMissingOrDefault(headingFont "");replaceIfMissingOrDefault(headingFont, ); int headingSize = getSize(request.getParameter("headingSize"), 32);32); String bodyFont = request.getParameter("bodyFont"); bodyFont =bodyFont replaceIfMissingOrDefault(bodyFont, ""); int bodySize = getSize(request.getParameter("bodySize"), 18);getS e( equest.get a a ete ( bodyS e ), 8); String fgColor = request.getParameter("fgColor"); fgColor = replaceIfMissing(fgColor, "BLACK");p g( g , ); String bgColor = request.getParameter("bgColor"); 32
  • 16. Résumé-Posting Site: Servlet Code (Continued)Servlet Code (Continued) private String replaceIfMissing(String orig,private String replaceIfMissing(String orig, String replacement) { if ((orig == null) || (orig.trim().equals(""))) { return(replacement);( p ) } else { return(orig); } } 33 Résumé-Posting Site: Result for Incomplete DataResult for Incomplete Data 34
  • 17. Filtering Strings for HTML- Specific Characters (Code)Specific Characters (Code) public class ServletUtilities { public static String filter(String input) {p g ( g p ) { if (!hasSpecialChars(input)) { return(input); } StringBuilder filtered =StringBuilder filtered = new StringBuilder(input.length()); char c; for(int i=0; i<input.length(); i++) { c = input.charAt(i); switch(c) { case '<': filtered.append("&lt;"); break; case '>': filtered append("&gt;"); break;case > : filtered.append( &gt; ); break; case '"': filtered.append("&quot;"); break; case '&': filtered.append("&amp;"); break; default: filtered.append(c); } } return(filtered.toString()); } …35 A Servlet that Displays Code Samples: No FilteringSamples: No Filtering @WebServlet("/code-preview-bad") public class CodePreviewBad extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { … out.println(docType + "<HTML>n" + "<HEAD><TITLE>"+title+"</TITLE></HEAD>n" + "<BODY BGCOLOR="#FDF5E6">n" + "<H1 ALIGN="CENTER">" + title + "</H1>n"+ "<PRE>n" + getCode(request) + "</PRE>n" + "Now, wasn't that an interesting samplen" + "of code?n" + "</BODY></HTML>"); }} protected String getCode(HttpServletRequest request) { return(request.getParameter("code")); } }36
  • 18. A Servlet that Displays Code Samples: No Special CharsSamples: No Special Chars 37 A Servlet that Displays Code Samples: Special CharsSamples: Special Chars 38
  • 19. A Servlet that Displays Code Samples: FilteringSamples: Filtering @WebServlet("/code-preview-good") public class CodePreviewGood extends CodePreviewBad {public class CodePreviewGood extends CodePreviewBad { protected String getCode(HttpServletRequest request) { return (ServletUtilities.filter(super.getCode(request))); } } 39 Fixed Servlet that Displays Code Samples: Special CharsCode Samples: Special Chars 40
  • 20. © 2010 Marty Hall Advanced Topics Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.41 Tags for Form Aesthetics • label – If you use the label tag for prompts associated with fields, clicking on the label transfers focus to the input field – You can either use the "for" attribute or enclose the field– You can either use the for attribute or enclose the field within the label • <label for="fname">First name:</label> <input type="text" name="userFirstName" id="fname"/><input type= text name= userFirstName id= fname /> • <label>First name: <input type="text" name="userFirstName" </label></label> • fieldset and legend – Grouping all or part of a form inside fieldset drawsGrouping all or part of a form inside fieldset draws attention to it and separates it from the rest of the page – Using style sheets for the legend is particularly useful42
  • 21. Tags for Form Aesthetics: ExampleExample • HTML <fieldset> <legend>ajax:updateField</legend> <form ...> <label for="f">Enter temperature in Fahrenheit:</label> <input type="text" id="f"/> <input type="button" id="convertButton" value="Convert"/> <hr width="500" align="left"/> <label for="c">Temperature in Celsius:</label> <input type="text" id="c"/> <l b l f "k">T t i K l i </l b l><label for="k">Temperature in Kelvin:</label> <input type="text" id="k"/> </form> </fieldset> CSS• CSS legend { font-weight: bold; color: black; background-color: white; border: 1px solid #cccccc; padding: 4px 2px; }43 Handling Input in Multiple LanguagesLanguages • Use server's default character set String firstName = request.getParameter("firstName"); C t f E li h (L ti 1) t J• Convert from English (Latin-1) to Japanese String firstNameWrongEncoding = request getParameter("firstName");request.getParameter( firstName ); String firstName = new String(firstNameWrongEncoding.getBytes(), "Shift JIS")"Shift_JIS"); • Accept either English or Japanese request setCharacterEncoding("JISAutoDetect");request.setCharacterEncoding( JISAutoDetect ); String firstName = request.getParameter("firstName"); 44
  • 22. Reading Raw Form Data and Parsing Uploaded FilesParsing Uploaded Files • Raw data – request.getReader – request.getInputStream • Data no longer available via getParameter after this• Data no longer available via getParameter after this • Parsing uploaded files – HTML has a way of submitting entire filesy g • <INPUT TYPE="FILE"…> – See Section 19.7 of 2nd Edition of Core Servlets and JSP. Servlet/JSP APIs have no builtin way to parse files– Servlet/JSP APIs have no builtin way to parse files – Popular third-party library available from the Apache/Jakarta “Commons” library • http://jakarta.apache.org/commons/fileupload/ 45 More Advanced Topics (See book for details/examples)(See book for details/examples) • Automatically filling in a data object with request parameter al esparameter values – Use a JavaBean (Java object with methods named getBlah and setBlah) to store incoming data – Request param named blah passed to appropriate setBlah method. Automatic type conversion. Default values used for errors. • Redisplaying the input form when parameters arep y g p p missing or malformed – The same servlet presents the form, processes the data, and presents the results. JSF provides better solution – see later tutorials!p • The servlet first looks for incoming request data: if it finds none, it presents a blank form. If the servlet finds partial request data, it extracts the partial data, puts it back intoq p p the form, and marks the other fields as missing. If the servlet finds the full complement of required data, it processes the request and displays the results.46
  • 23. Summary • Make a form: <form …> … </form> – Relative URL for “action”. Textfields need “name”. Should always have submit button. • Read data: request getParameter("name")• Read data: request.getParameter( name ) – Results in value as entered into form, not necessarily as sent over network. I.e., not URL-encoded. • Check for missing or malformed data – Missing: null or empty string – Special case: query data that contains special HTML characters • Need to be filtered if query data will be placed intoNeed to be filtered if query data will be placed into resultant HTML page 47 © 2010 Marty Hall Questions? Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Struts, Ajax, GWT 2.0, Spring, Hibernate, SOAP & RESTful Web Services, Java 6. Developed and taught by well-known author and developer. At public venues or onsite at your location.48