390 likes | 571 Views
Web App GUI: JSP Basics & Forms . 3680 Enterprise Programming. Overview. Taking User Input <form> tag <input> tag Processing User Input Server-side scripting – JSP JSP expression, scriptlet Validating User Input Client-side scripting - JavaScript. Paradigm for User Input Processing.
E N D
Web App GUI: JSP Basics & Forms 3680 Enterprise Programming
Overview • Taking User Input • <form> tag • <input> tag • Processing User Input • Server-side scripting – JSP • JSP expression, scriptlet • Validating User Input • Client-side scripting - JavaScript
HTML Form • User input is entered in an HTML <form>. • A form has three key attributes. • Name: • Required if you have multiple forms on the same page. • It is customary to name it any ways. • Action: • Specify the destination file where the form is processed. It can be a Java servlet, a JSP page, or an ASP.NET page, etc. • If you don’t specify an action, the form will do nothing. • Method: • Specify how to send form to the Web server, either POST or GET.
Input Field • Each input field (a.k.a. “control”, “control field”, etc.) in a form is defined using the <input> tag (with few exceptions). • For example, <form name="main" action="processUserName.jsp" method="post"> Your Last Name:<input type="text" name="lastName" /> </form>
Input Attributes • TYPE: • Specifies the input type, e.g., text (for textboxes), checkbox, etc. • NAME: • Each control in a form must have a NAME. The data entered by the user is retrieved by referencing the name of the field. Without a name, the data stored in the field cannot be retrieved. • Name is the identifier so that you can pass more than one field and the server will know which field is which. • VALUE: • The value attribute you define at coding time is the initial (default) value may be assigned to a field. • This often is replaced by the dynamic value entered by user.
Input Types • Text/Password – textbox • Checkbox – Checkbox (non-mutually exclusive choice) • Radio – Radio button (mutually exclusive choice) • Submit – “Submit” button • A submit button enables you to actually send the form to the server. • Its “value” attribute only changes the text label on the button’s face. If you don’t set it, the default text is “Submit Query”, which may be too geeky for normal users. • Its “name” attribute really doesn’t matter.
Textbox • Use text for the type attribute.
Checkbox • Checkboxes can be use for non-mutually exclusive options.
Radio Buttons • Use <input> element and set its type to “radio”. • Use one <input> element for each radio (selectable item). • The label you want to appear next to the radio button is the text enclosed between <input> and </input> tags. • For all radio buttons that belong in the same group (a mutually exclusive set of items), the “name” attribute of their <input> element must be the same. That is, the name identifies the entire set, not an individual radio. • Each <input> element, however, must have a unique value for its “value” attribute. • The value of the selected radio will be passed to the “action” page.
Radio Buttons <p>Gender: <input type="radio" name="gender" value="M">Male</input> <input type="radio" name="gender" value="F">Female</input></p>
Submit Button • Use Submit for the type attribute (avoid button). • The value of the value attribute is the text that appears on the face of the button.
Processing Input with Dynamic Pages • To actually process user input passed in a <form>, we need to write Java code. • A dynamic Web page contains both static (template) text and dynamic contents. Static text is written in plain HTML. • The dynamic contents are generated by Java code written as JSP elements. • The goal of JSP is to generate the dynamic data and insert them into the correct spots in static HTML.
JavaServer Pages • The file extension must be .jsp instead of .htm/.html. • You can make a pure HTML page a “JSP” file simply by changing its file extension to .jsp. • The reverse is not true. For an HTML page containing JSP code to function as intended, you cannot use the .htm/.html extension. • Behind the scene, the server actually converts your JSP file containing Java code into a servlet. • But we don’t write Java code in JSP explicitly as classes. • JSP files contains scripts in Java syntax. Not JavaScript. • JavaScript is client-side scripting. JSP is server-side scripting.
Implicit Objects • In a JavaServer page, some useful, oft-used objects are created automatically for you so that you don’t have to worry about instantiating those objects. • Three of them are of particular interest to us: • The request object – contains information about the request made by the client (browser) to the Web server. • The response object – controls output the Web server sends to the client. • The out object – generates text that is being sent to the client.
The request Object • We can extract useful information from the request object. • Its HTTP header – Metadata about the HTTP request sent by the web browser, such as the browser type and session ID. • The IP and DNS addresses of the client machine. • Locale information about the client machine, e.g., language, country, etc. • Whether the client is using GET or POST to request the page.
The out Implicit Object • There is an implicit out object in every JSP page. It’s an instance of the javax.servlet.jsp.JspWriter class. • It has a println() and a print() method that can be used to spit out text contents.
JSP Expression • Not a complete Java statement, and not HTML code for sure. • Written in Java syntax but does not end with semicolon. • Dynamically takes on value during web app execution, based on user input, current date/time, etc. • Ideal for filling in “placeholder” spots in HTML with real values, e.g., an HTML <td> element for unit price may be written as <td><%= unitPrice %></td> in design time. • In run time, it gets a real value for the “placeholders”. For example, the above <td> element may become <td>27.99</td> if, before the expression is run, the variable unitPrice has taken on a value of 27.99.
Scriptlet • Contains complete Java statement(s). Each statement ends with a semicolon. • Much more powerful than expressions. Can create objects, do calculation, manipulate strings, run loops, handle conditions, etc. • Some times you can stretch your expressions to do these, but not without making your code Klingon (FYI, a small handful of people on this planet speak fluent Klingon). • A typical setup is to have complex code handled by scriptlets, often as a large chunk at the top. Then, expressions interspersed with the HTML code refer to variables in those scriptlets whenever necessary.
Writing HTML Code Programmatically • Both JSP expressions and scriptlets can be used to output HTML code, with important differences.
Processing User Input • To create dynamic pages, an important task is to extract the values entered by the users. • When the form is submitted, each piece of user input (the values entered into the <input> tags) are passed as a parameter. • A parameter is in the form of a name-value pair. • The name is the name attribute you defined for the <input> tag. • The value is the information furnished by the user, e.g., text entered into a textbox.
Processing User Input • For example, a text input field is called “firstName” and a particular user enters “Andy” on the page. • The name-value pair is firstName=Andy. • The parameter is the “firstName” parameter. • If multiple parameters are passed, they are connected with ampersands. • The collection of parameters is called a query string, preceded with a question mark. e.g., ?firstName=Andy&lastName=Wu • Parameters are stored in the request object and passed to the next page. • Parameter names are case-sensitive.
getParameter() Method • To retrieve the value stored in this parameter, call the getParameter() method of the request object. • Pass the parameter name as the argument. • getParameter("firstName")will return the value “Andy”. • This is the same regardless of which method (get or post) is used to submit the form.
Data Type of Parameter Values • If a parameter does have content, i.e., not being passed as null, the getParameter() method returns a String. • Even numeric data entered by users are passed as Strings. • Call the parseX() methods in wrapper classes to convert the textual information into numeric, e.g., intorderQty = Integer.parseInt( request.getParameter("qty") ); • It often helps to run an if statement to check whether a parameter is null before calling the getParameter() method.
Get vs. Post • After a form is submitted, the browser moves away from the current page to the page specified in the action attribute of the form. • In the address bar, the browser displays the file name of the page where processing of the form takes place. • It may or may not append extra information to the end of that URL, depending on whether the form action is a Get or a Post.
Get vs. Post • If it’s a get, the query string is appended (a question mark, followed by name-value pairs in the format of fieldName=fieldValue, separated by ampersands). • If it’s a post, nothing will be appended to the URL.
Validating User Input • At times we want to validate user input to make sure the information is entered in the correct format, the value falls within logically valid range, required information is provided, etc. • In some situations validation may be done on the server side again, but most likely we want to perform validation on the client (browser) so that we don’t add unnecessary burden to the server. • Client-side user validation usually is done with JavaScript.
Client- vs. Server-Side Scripting • An HTML form consists of one or more input fields into which the user enters the necessary information. • You use an HTML form to collect information from the user. • Client-side Scripting: You often want to validate the input using JavaScript. • You pass the information to the sever. • Server-side Scripting: The server processes user input, creates dynamic contents based on the input, and writes the HTML code. • The server passes the generated code back to the client. • The client’s browser displays the HTML code from the server.
JavaScript • Preferred choice for client-side validation. • Not a “watered-down” version of Java. They were actually created by different companies. But the syntax is very similar. • Much more relaxed (or lax) in terms of variable declaration, data type, argument passing, etc. • But still is case-sensitive.
Placement of Scripts • You can insert JavaScript code into multiple locations in the page, using more than one <script> tags. • If part of our HTML code or a <script> tag depends on the result from executing another <script> tag, that other <script> tag must be placed ahead of the current code. • The <script> tag content in the <head> section gets loaded before the remaining parts of the page.
Client-side Scripting Using JavaScript <script language="JavaScript"> document.write("Hello World!") </script> Opening script tag Closing tag
Inserting Comments into Client-side Scripts <script language="JavaScript"> <!-- Hide script from old browser /* This script adds the words "Hello World!" into the body area of the HTML page */ document.write("Hello World!") //End hiding script from old browser--> </script> Make your code more readable
Referencing An Object in JavaScript • JavaScript defines a hierarchy for objects on a page, e.g., • The “firstName” text box in a form called “main” is referred to as: documents.forms.main.firstName • The value user types into the text box is referred to as: documents.forms.main.firstName.value
JavaScript Functions • A function is a set of JavaScript instructions or operations that perform a task. • Every function has a unique name, and can be invoked, or called, by other parts of the script. • The benefits of using functions are about the same as those of using methods in Java: • Use a single command to trigger a complex series of actions. • Prevent from repeating the code a number of times within the script. • Develop generic functions that you can reuse in any script.
JavaScript Functions Syntax • Defining a function function functionName(arguments) { … } • To call a function functionName(arguments)
Events and Scripts • An event is a user action that triggers activities on the page. • For example, loading a Web page when it is requested, clicking a button on a Web page, moving a mouse over an image, and typing into a text input field on a form, are all events • You can write script to respond to specific actions or events. • You can attach a script to some visible element so that the script is executed when the user performs an action on that element (for example, clicking it).
Events and Scripts • To respond to an event in a Web page, you need: • An event - User action that triggers an event handler (e.g., mouse click). • An event handler - Script that respond to the action, typically a JavaScript function. • An association of the two by adding an attribute in the format of event_name = function_call_statement to the tag.