2011 Marty Hall
Originals of Slides and Source Code for Examples: http://courses.coreservlets.com/Course-Materials/csajsp2.html
Customized Java EE Training: http://courses.coreservlets.com/
2
Handling the Client Request: Form Data q
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
2011 Marty Hall
Servlets, JSP, JSF 2, Ajax (with jQuery, Dojo, Prototype, Ext-JS, etc.), GWT, Java 6, SOAP-based and RESTful Web Services, Spring, Hibernate/JPA, Android, Hibernate/JPA Android and customized combinations of topics topics.
For live Java EE training, please see training courses at http://courses.coreservlets.com/. http://courses coreservlets com/
Taught by the author of Core Servlets and JSP, More Servlets and JSP and this tutorial. Available at public JSP, tutorial venues, or customized versions can be held on-site at your Customized Java EE Training: http://courses.coreservlets.com/ Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. organization. Contact [email protected] for details. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Agenda
The role of form data Creating and submitting HTML forms g q p Reading individual request parameters Reading the entire set of request parameters Handling missing and malformed data Dealing with incomplete form submissions Filtering special characters out of the request parameters
2011 Marty Hall
Form Basics
Customized Java EE Training: http://courses.coreservlets.com/
5
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
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
Read the data one way (QUERY_STRING) for GET requests, another way (standard input) for POST requests q , y( p ) OS q Chop pairs at ampersands, then separate parameter names (left of the =) from parameter values (right of the =) URL d d values ( decode l (e.g., "%7E" b becomes " ") "~")
Greatly simplified in servlets
Use request getParameter in all cases. request.getParameter cases Gives URL-decoded result
6
Creating Form Data: HTML 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>
<FORM ACTION="http://localhost:8088/SomeProgram"> <CENTER> 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>
You normally use a relative URL for the ACTION. This URL is just for testing because I am running a test server on port 8088 that echoes the data it receives.
See CSAJSP/2 Ch. 19 for details on forms
Aside: Installing HTML Files
HTML files do not go in src
They go in WebContent
When deployed, that becomes the top-level Web application directory pp y In contrast, code under src gets deployed to the WEB-INF/classes folder of the Web app directory
Example
Eclipse project name: forms Files
WebContent/test1.html WebContent/someDir/test2.html
URLs
8
http://localhost/forms/test1.html http://localhost/forms/someDir/test2.html
GET Form: Initial Result
GET Form: Submission Result (Data Sent to EchoServer)
10
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" The default method is GET. So, if a form says METHOD="GET" or it METHOD="POST"> has no METHOD at all, GET is used. <CENTER> First name: <INPUT TYPE="TEXT" NAME="firstName" VALUE="J. Random"><BR> Last name: <INPUT TYPE="TEXT" NAME="lastName" VALUE="Hacker"><P> TYPE= TEXT NAME= lastName VALUE= Hacker ><P> <INPUT TYPE="SUBMIT"> </CENTER> </FORM> </BODY></HTML>
11
POST Form: Initial Result
12
POST Form: Submission Result (Data Sent to EchoServer)
13
GET vs. POST
Advantages of POST
URL is simpler Data is hidden from people looking over your shoulder Larger amounts of data can be sent Can send special characters (e.g., in uploaded files) Browsers will not cache results Should always be used if the requests changes data on server (REST)
Ad Advantages of GET t f
Can bookmark results page Browsers can cache results Easier to test interactively
14
HTML 4 vs. XHTML Syntax
HTML 4
S Some end t d tags optional ti l 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 co ve e ce, a d o ow convenience, and follow XHTML syntax in their pages. sy a e
Examples
HTML 4
<INPUT TYPE= TEXT NAME="Blah"><BR> TYPE="TEXT" NAME= Blah ><BR>
XHTML
<input type="text" name="Blah"/><br/>
15
2011 Marty Hall
Reading Form Data
Customized Java EE Training: http://courses.coreservlets.com/
16
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Reading Form Data In Servlets
request.getParameter("name")
R t Returns URL-decoded value of first occurrence of name URL d d d l f fi t f in query string Works identically for GET and POST requests Returns null if no such parameter is in query data 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 Returns null if no such parameter is in query ll h t i i Returns Enumeration or Map of request params Usually reserved for debugging
17
request.getParameterValues("name")
request.getParameterNames() or q g p() request.getParameterMap()
An HTML Form With Three Parameters
<FORM ACTION="three-params"> First Parameter: <INPUT TYPE="TEXT" NAME="param1"><BR> 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: Result
20
Reading All Parameters
@WebServlet("/show-params") p public class ShowParameters extends HttpServlet { p public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); ( / ) PrintWriter out = response.getWriter(); String docType = <!DOCTYPE \ //W3C//DTD "<!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>" </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)
Enumeration<String> paramNames = request.getParameterNames(); while(paramNames.hasMoreElements()) { String paramName = (String)paramNames.nextElement(); out.print("<TR><TD>" + paramName + "\n<TD>"); String[] paramValues = request.getParameterValues(paramName); req est getParameterVal es(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]); } p out.println("</UL>"); } } out.println("</TABLE>\n</BODY></HTML>");
22
Reading All Parameters (Continued)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException IOException { ServletException, doGet(request, response); } }
23
Reading All Parameters (Sample Form)
24
Reading All Parameters (Result)
25
2011 Marty Hall
Handling Missing and Malformed Data
Customized Java EE Training: http://courses.coreservlets.com/
26
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
Checking for Missing and Malformed Data
Missing
Field missing in form
getParameter returns null
Field blank when form submitted
getParameter returns an empty string (or possibly a string with whitespace in it)
M t check for null before checking for empty string Must h k f ll b f h ki f t ti
String param = request.getParameter("someName"); if ((param == null) || (param.trim().equals(""))) { doSomethingForMissingValues(...); doSomethingForMissingValues( ); } else { doSomethingWithParameter(param); }
Malformed
27
Value is a nonempty string in the wrong format
Checking for Missing and Malformed 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 create,
28
Handling Missing and Malformed Data
Use default values Redisplay the form
Replace missing values with application-specific standard values application specific See following example Show the form again with missing values flagged again, Previously-entered values should be preserved Best option for implementing this: use framework like JSF or Struts
Covered in later tutorials
Four options to implement this directly
S book f example See b k for l
Have the same servlet present the form, process the data, and present the results. 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 page process the d t and present the results. th data d t th lt 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 Rsum-Posting Site
30
Rsum-Posting Site: Input Form and Good Data Results
31
Rsum-Posting Site: Servlet Code
headingFont = replaceIfMissingOrDefault(headingFont, replaceIfMissingOrDefault(headingFont ""); ); int headingSize = getSize(request.getParameter("headingSize"), 32); String bodyFont = request.getParameter("bodyFont"); bodyFont = replaceIfMissingOrDefault(bodyFont, ""); int bodySize = getS e( equest.get a a ete ( bodyS e ), 8); getSize(request.getParameter("bodySize"), 18); String fgColor = request.getParameter("fgColor"); fgColor = p g( g , ); replaceIfMissing(fgColor, "BLACK"); String bgColor = request.getParameter("bgColor");
32
Rsum-Posting Site: Servlet Code (Continued)
private String replaceIfMissing(String orig, String replacement) { if ((orig == null) || (orig.trim().equals(""))) { ( p ) return(replacement); } else { return(orig); } }
33
Rsum-Posting Site: Result for Incomplete Data
34
Filtering Strings for HTMLSpecific Characters (Code)
public class ServletUtilities { p public static String filter(String input) { g ( g p ) if (!hasSpecialChars(input)) { return(input); } 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("<"); break; case '>': filtered append(">"); break; > : filtered.append( > ); case '"': filtered.append("""); break; case '&': filtered.append("&"); break; default: filtered.append(c); } } return(filtered.toString()); }
35
A Servlet that Displays Code Samples: 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 sample\n" + "of code?\n" + "</BODY></HTML>"); } protected String getCode(HttpServletRequest request) { return(request.getParameter("code")); } }
36
A Servlet that Displays Code Samples: No Special Chars
37
A Servlet that Displays Code Samples: Special Chars
38
A Servlet that Displays Code Samples: Filtering
@WebServlet("/code-preview-good") public class CodePreviewGood extends CodePreviewBad { protected String getCode(HttpServletRequest request) { return (ServletUtilities.filter(super.getCode(request))); } }
39
Fixed Servlet that Displays Code Samples: Special Chars
40
2011 Marty Hall
Advanced Topics
Customized Java EE Training: http://courses.coreservlets.com/
41
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.
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 for within the label
<label for="fname">First name:</label> <input type= text name="userFirstName" id="fname"/> type="text" name= userFirstName id= fname /> <label>First name: <input type="text" name="userFirstName" </label>
fieldset and legend
Grouping 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 useful
42
Tags for Form Aesthetics: Example
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"/> <label for="k">Temperature i K l i </l b l> <l b l f "k">T t in Kelvin:</label> <input type="text" id="k"/> </form> </fieldset>
CSS
43
legend { font-weight: bold; color: black; background-color: white; border: 1px solid #cccccc; padding: 4px 2px; }
Handling Input in Multiple Languages
Use server's default character set
String firstName = request.getParameter("firstName");
C Convert f t from E li h (Latin-1) t J English (L ti 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 Files
Raw data
request.getReader request.getInputStream
Data no longer available via getParameter after this
Parsing uploaded files
HTML has a way of submitting entire files y 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 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)
Automatically filling in a data object with request parameter values al es
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 are p 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 p q partial data, p puts it back into 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") 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 into resultant HTML page
47
2011 Marty Hall
Questions?
Customized Java EE Training: http://courses.coreservlets.com/
48
Servlets, JSP, JSF 2.0, Java 6, Ajax, jQuery, GWT, Spring, Hibernate, RESTful Web Services, Android. Developed and taught by well-known author and developer. At public venues or onsite at your location.