380 likes | 496 Views
CSCI 6962: Server-side Design and Programming. Introduction to Java Server Pages. Server Page Model. Html document with executable code interspersed When page requested: Code executed Html generated and inserted in its place Final all html document sent back as response.
E N D
CSCI 6962: Server-side Design and Programming Introduction to Java Server Pages
Server Page Model • Html document with executable code interspersed • When page requested: • Code executed • Html generated and inserted in its place • Final all html document sent back as response Glassfish server somepage.jsp html html Java html Java html html html html Java html html request for somepage.jsp resulting html page html html html html html html html html html html html html
JSP Syntax • Basic tag form: <% … %> • Simplest form:<%=some Java expression %> • Glassfish evaluates expression to get value • Inserts that value in place of expression in generated html page
JSP Simple Example • Simple example: Java Server Page 2 + 2 evaluated to value of 4 Resulting html Page
Scriptlets • Basic tag form: <% … %> • Executes code inside brackets without generating html • Set variables later used to generate html later • Store/access values in session/databases
Scriptlets Stores value of 4 in sum variable Value of 4 in sum used in this JSP No html here
JSP Scoping • Variable declared in a block of JSP on a page • May be accessed by any other JSP on same page • No access to variable from any other page (purpose of sessions)
Simple Form Elements • The FORM tag<form action=”url of response page” method=”get or post”>…</form> • TEXTtag<input type=“text” name = “elementname” /> • SUBMITtag<input type=”submit” value=”buttonlabel”/>
Form Element Example <form action="orderReply.jsp" method="get"> <table cellspacing="5"> <tr> <td align="right">Number to purchase:</td> <td><input type="text" name="quantity"></td> </tr><tr> <td align="right">Your name:</td> <td> <input type="text" name="customerName"></td> </tr><tr> <td align="right">Your email:</td> <td> <input type="text" name="customerEmail"></td> </tr><tr> <td></td> <td><input type="submit" value="Place Order"></td> </tr> </table> <form>
Form Parameter Passing Parameter string passed:quantity=137&customerName=John+Sullins&customerEmail=john@cis.ysu.edu
Handling Form Data • requestobject in JSP • Java object created from request string • Contains request data and methods to easily access that data • Accessed by JSP code request Data from form Other data about request methods to access data Code in JSP
Handling Form Data • Most useful method:Stringrequest.getParameter(String) • Example:String name = request.getParameter("customerName");sets the value of “name” to “John Sullins” Returns the corresponding value passed to the server Takes name of form element as parameter
Example JSP <body> <% String name = request.getParameter("customerName"); String email = request.getParameter("customerEmail"); String quantity = request.getParameter("quantity"); %> <h2>Order Confirmation</h2> <p> Thank you for your order of<%= quantity %>widgets,<%= name %>. </p> <p> You will shortly receive an email confirmation at <%= email %>. </p> </body>
Acquiring Form Data • Statements to get and store form data:<% String name = request.getParameter("customerName"); String email = request.getParameter("customerEmail"); String quantity = request.getParameter("quantity"); %>
Displaying Values in Response <p> Thank you for your order of <%= quantity %> widgets,<%= name %>. </p><p> You will shortly recieve an email confirmation at<%= email %>. </p> John Sullins 137 john@cis.ysu.edu
Parsing Numeric Input • getParameter method returns a String • Must parse strings into numbers before performing numeric computations This is “5”, not the number 5!
Parsing Numeric Input Useful built-in methods: • Parsing a whole number string (such as “57”):intInteger.parseInt(String) • Parsing a decimal string (such as “5.7”)double Double.parseDouble(String) • Example:String quantity = request.getParameter(“quantity”);intquantityNumber = Integer.parseInt(quantity);
Numeric Input Example <% String name = request.getParameter("customerName"); String email = request.getParameter("customerEmail"); String quantity = request.getParameter("quantity"); double pricePerUnit = 9.95; intquantityNumber = Integer.parseInt(quantity); double totalCost = pricePerUnit * quantityNumber; %> <h2>Order Confirmation</h2> <p>Thank you for your order of<%= quantity %>widgets, <%= name %>.</p> <p>At$<%= pricePerUnit %>,your bill will be $<%= totalCost %>.</p> <p>You will shortly receive an email confirmation at <%= email %>.</p>
Complex Input Elements • Checkboxes • Radio Buttons • Lists
Checkbox HTML • Basic form:<INPUT TYPE="checkbox“ NAME="monitor">Monitor • String passed to server: • “ …monitor=on… ” if monitor is checked • No mention of monitor if not checked
Checkbox JSP • If execute JSP code:String monitor = request.getParameter("monitor");monitor will have the value • “on” if the checkbox was checked • null if the checkbox not checked • null is always returned if ask for value of parameter which was not passed in the request string
Conditions in Java if(condition) { statements to execute if true }else { statements to execute if false }
Inline Conditional HTML Display • Display different html based on condition • Put html in conditional statement • Must use <% and %> to differentiate Java, html <% if (condition) { %> html to display if condition true <% } else { %> html to display if condition false <% } %>
Conditions in Scriptlet • Alternative: Build string to display in prior Java code <% String monitor = request.getParameter(“monitor”); String monitorDisplay = “”; if (monitor != null) {monitorDisplay = “ with monitor ”; }…Total cost of <%= memory %> GB computer <%= monitorDisplay %> is <%= cost %>. “” if monitor not checked “with monitor” if monitor checked
Radio Button HTML • Convention: Only one in group checked • Must give all in group same name • Must give each different value <input type="radio" name=“memory"value=“8“/>8 GB <input type="radio" name=“memory"value=“4">4 GB
Radio Button JSP • Sent in form …name=value… to server • memory=4 • memory=8 • Can access value using:String processor = request.getParameter(“memory");And display in html:
String Comparison • .equals method to compare strings in Javaif (string1.equals(string2) { …
List HTML • Basic form:<SELECT NAME=“listname” SIZE=“numvisible”> <OPTION VALUE=“value1”/> label1 <OPTION VALUE=“value2”/> label2 …</SELECT>
List JSP • Sent in form …name=value… to server • software=Adobe+Reader • Software=Office+2013 • Software=Norton+Antivirus • If single option selected, similar to radio buttons
Multiple Selection Lists • Can allow user to select multiple options from listwith multiple attribute<select name=“software" multiple=“multiple”> • Sends name=value string for each option selected…software=Adobe+Reader&software=Norton… • getParameter method will not work!
JSP for Multiple Selection Lists • String[]request.getParameterValues(String name) • Example:String [] peripherals = request.getParameterValues("peripherals");creates the array: Returns array of values passed for this name peripherals
Looping Through Arrays • Often use loop to process all values selected • Basic form in Java:for (inti = 0; i < arrayname.length; i++) { code to process ith element of arrayname } • Can use to display html multiple times<% for (inti = 0; i < arrayname.length; index++) { %> html created from ith element of arrayname <% } %> Note: Java has built-in length property for array which evaluates to its size
Looping Through Arrays in JSP • Example:<% for (inti = 0; i < software.length; i++) { %> <%= software[i] %><br\> <% } %> For each value in the softwarearray Display that value in html software[0] software[1]
Null Input • User may not choose any value in list! • software will have value null • Accessing null value gives run time exception • Must check for this before processing array
Detecting null Input Basic form of code:if (variable != null) { code for case where user chose a value } else { code for case where none selected } Note that best solution might be redirecting to an error page!
Checking for NULL Lists • Example: <% if (software != null) { %> <% for (inti = 0; i < software.length; i++) { %> <%= software[i] %><br> <% } %> <% } else { %> <i>No software chosen</i> <% } %> Only executed if array exists
Commenting JSP Files • Crucial to future maintenance of site • Inside of JSP code (between <% and %>):// comment/* comment */ • Outside of JSP code (that is, in html)<!-- comment -->
Importing Library Classes • Much of Java classes in separate libraries • Must be imported to be used in JSP • Syntax:<%@ page import=”list of Java classes” %> • Example:<%@ page import=”java.util.Date, java.io.*” %> Date class in the util library All classes in the io library