ServerSide Scripting with Java Server Page JSP ISYS

  • Slides: 44
Download presentation
Server-Side Scripting with Java Server Page, JSP ISYS 350

Server-Side Scripting with Java Server Page, JSP ISYS 350

Java Website • Java Tutorial: – http: //docs. oracle. com/javase/tutorial/ • JSP, Servlet tutorial:

Java Website • Java Tutorial: – http: //docs. oracle. com/javase/tutorial/ • JSP, Servlet tutorial: – http: //www. jsptut. com/ – http: //docs. oracle. com/javaee/5/tutorial/doc/bna gx. html – http: //www. javatpoint. com/servlet-tutorial

Java Platforms • Java SE (Standard Edition) provides the core functionality of the Java

Java Platforms • Java SE (Standard Edition) provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, etc. • Java EE (Enterprise Edition) is built on top of the Java SE platform for developing and running large-scale, multitiered, scalable, reliable, and secure network applications. • Java ME (Mobile Edition) provides an API and a small- footprint virtual machine for running Java programming language applications on small devices, like mobile phones.

Hyper Text Transfer Protocol: Request & Response HTTP Request Web Server Browser HTTP Response

Hyper Text Transfer Protocol: Request & Response HTTP Request Web Server Browser HTTP Response Web Application

Use JSP to Process a Form

Use JSP to Process a Form

FORM • Form attribute: – Action: Specify the URL of a program on a

FORM • Form attribute: – Action: Specify the URL of a program on a server or an email address to which a form’s data will be submitted. – Method: Post/Get – Get: the form’s data is appended to the URL specified by the Action attribute as a Query. String. – Post: A preferred method for database processing. Form’s data is sent in the HTTP body. Post is the preferred method. Example: <form name="test. Form" method="post" action="compute. Sum. jsp“> • Button: – Type = “submit” <input type="submit" value="Compute. Sum. JSP" name="btn. Compute"/>

Query. String • A Query. String is a set of name=value pairs appended to

Query. String • A Query. String is a set of name=value pairs appended to a target URL. • It can be used to pass information from one webpage to another. • To create a Query. String: – Add a question mark (? ) immediately after a URL. – Followed by name=value pairs separated by ampersands (&). • Example: • <A Href=“http: //my. com/Target. htm? Cust. ID=C 1&Cname=Chao”>

Data Sent with Request and Response • Request: – requested URL, cookies, query. String,

Data Sent with Request and Response • Request: – requested URL, cookies, query. String, data from a form, etc. • Response: – Web page content in HTML code – Cookies – Etc.

Java Server Pages, JSP • Java Server Pages (JSP) is a technology that lets

Java Server Pages, JSP • Java Server Pages (JSP) is a technology that lets you mix regular, static HTML with dynamicallygenerated HTMLrequest: • JSP objects: – Request object: retrieves the values that the client browser passed to the server during an HTTP request – Response object: This denotes the HTTP Response data. – Session: This denotes the data associated with a specific session of user. The main use of Session Objects is for maintaining states when there are multiple page requests. – Out object: print, println

Methods of request Object • get. Parameter(String name): Returns the value of a request

Methods of request Object • get. Parameter(String name): Returns the value of a request parameter as a String, or null if the parameter does not exist. • get. Query. String(): Gets any query string that is part of the HTTP request URI. • get. Cookies(): Gets the array of cookies found in this request. • get. Request. URI(): Gets the URI to the current JSP page. • etc.

Methods of response Object • add. Cookie(Cookie): Adds the specified cookie to the response.

Methods of response Object • add. Cookie(Cookie): Adds the specified cookie to the response. It can be called multiple times to set more than one cookie. • send. Redirect(String): Sends a temporary redirect response to the client using the specified redirect location URL.

JSP Out Object • print: The print method of out object writes the value

JSP Out Object • print: The print method of out object writes the value to the output without a newline character. out. print("Welcome!!!"); out. print("To JSP Training"); Output is: Welcome!!! To JSP Training

JSP scriptlet <% %> Example: <body> <h 1>Hello World!</h 1> <% out. print("Welcome!!!"); out.

JSP scriptlet <% %> Example: <body> <h 1>Hello World!</h 1> <% out. print("Welcome!!!"); out. print("To JSP Training"); %> </body> Question: How to start a new line? out. print(" To JSP Training");

In addition to the eight primitive data types listed above, the Java programming language

In addition to the eight primitive data types listed above, the Java programming language also provides special support for character strings via the java. lang. String class. String s = "this is a string"; .

Compute the Sum of 2 Numbers:

Compute the Sum of 2 Numbers:

Form Example <body> <div>Compute the sum of two numbers</div> <form name="test. Form" method="post" action="compute.

Form Example <body> <div>Compute the sum of two numbers</div> <form name="test. Form" method="post" action="compute. Sum. jsp"> Enter num 1: <input type="text" name="num 1" value="" /> Enter num 2: <input type="text" name="num 2" value="" /> <input type="submit" value="Compute. Sum. JSP" name="btn. Compute"/> </form> </body> Notre 1: The form has a method property nd action property. Note 2: The button now is type: submit, and there is no onclick event.

Example of JSP scriptlet <% %> Compute the Sum of 2 Numbers: <body> <%

Example of JSP scriptlet <% %> Compute the Sum of 2 Numbers: <body> <% String value 1, value 2; double n 1, n 2, sum; value 1=request. get. Parameter("num 1"); value 2=request. get. Parameter("num 2"); n 1= Double. parse. Double(value 1); n 2= Double. parse. Double(value 2); sum=n 1+n 2; out. print("The sum is: " + sum); %> </body> Note 1: Double is an object that offers the parse. Double method, not “double” data type. Note 2: “out” is an implicit object that does not need to be declared. It is already predefined.

Example of get Method and get. Query. String() <% String value 1, value 2;

Example of get Method and get. Query. String() <% String value 1, value 2; double n 1, n 2, sum; String query. String=request. get. Query. String(); value 1=request. get. Parameter("num 1"); value 2=request. get. Parameter("num 2"); n 1= Double. parse. Double(value 1); n 2= Double. parse. Double(value 2); sum=n 1+n 2; out. print("The sum is: " + sum); out. print(" The query. String is: " + query. String); %>

Writing HTML code as output <body> <% String value 1, value 2; double n

Writing HTML code as output <body> <% String value 1, value 2; double n 1, n 2, sum; value 1=request. get. Parameter("num 1"); value 2=request. get. Parameter("num 2"); n 1= Double. parse. Double(value 1); n 2= Double. parse. Double(value 2); sum=n 1+n 2; out. print(" <p>Value 1: <input type=‘text' name='num 1' size='20' value='" + value 1 + "'></p>"); out. print(" <p>Value 2: <input type='text' name='num 2' size='20' value='" + value 2 + "'></p>"); ); out. print("The sum is: <input type='text' name='sum' size='20' value='" + sum + "'>" %> </body>

Embed JSP code in HTML Using JSP Expression: <%= %> <% String value 1,

Embed JSP code in HTML Using JSP Expression: <%= %> <% String value 1, value 2; double n 1, n 2, sum; value 1=request. get. Parameter("num 1"); value 2=request. get. Parameter("num 2"); n 1= Double. parse. Double(value 1); n 2= Double. parse. Double(value 2); sum=n 1+n 2; %> <form method="POST" name="test. Form" > <p>Value 1: <input type="text" name="num 1" size="20" value="<%=value 1%>"></p> <p>Value 2: <input type="text" name="num 2" size="20" value="<%=value 2%>"></p> <p> Sum is: <input type="text" name="num 2" size="20" value="<%=sum%>"></p> </form>

Import Java Class Example: Display Current Date Time • Import java. util. Date –

Import Java Class Example: Display Current Date Time • Import java. util. Date – <%@page import="java. util. Date"%> • Define a Date type variable: – Date current. Date = new Date(); • Display in textbox using JSP expression: <p>The time is: <input type="text" name="num 2" size="20" value="<%=current. Date%>"></p>

Code Example <%@page import="java. util. Date"%> <%@page content. Type="text/html" page. Encoding="UTF-8"%> <html> <head> <meta

Code Example <%@page import="java. util. Date"%> <%@page content. Type="text/html" page. Encoding="UTF-8"%> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF 8"> <title>JSP Page</title> </head> <body> <% Date current. Date = new Date(); %> <p>The time is: <input type="text" name="num 2" size="20" value="<%=current. Date%>"></p> </body> </html>

Compute Future Value: Process form with various controls

Compute Future Value: Process form with various controls

Form Code <form name="fv. Form" method="post" action="compute. FV. jsp"> Enter present value: <input type="text"

Form Code <form name="fv. Form" method="post" action="compute. FV. jsp"> Enter present value: <input type="text" name="PV" value="" /> Select interest rate: <select name="Rate"> <option value=. 04>4%</option> <option value=. 05>5%</option> <option value=. 06>6%</option> <option value=. 07>7%</option> <option value=. 08>8%</option> </select> Select year: <input type="radio" name="Year" value="10" />10 -year <input type="radio" name="Year" value="15" />15 -year <input type="radio" name="Year" value="30" />30 -year <input type="submit" value="Compute. FVJSP" name="btn. Compute" /> </form>

JSP Code Example <body> <% String my. PV, my. Rate, my. Year; my. PV=request.

JSP Code Example <body> <% String my. PV, my. Rate, my. Year; my. PV=request. get. Parameter("PV"); my. Rate=request. get. Parameter("Rate"); my. Year=request. get. Parameter("Year"); double FV, PV, Rate, Year; PV=Double. parse. Double(my. PV); Rate=Double. parse. Double(my. Rate); Year=Double. parse. Double(my. Year); FV=PV*Math. pow(1+Rate, Year); out. print("Future. Value is: "+ FV); %>

Use Client-Side Validating and Sumbit Validated Form <script > function Validating(){ var Valid; Valid=true;

Use Client-Side Validating and Sumbit Validated Form <script > function Validating(){ var Valid; Valid=true; if (document. fv. Form. PV. value=="") {Valid=false; } if (Valid==false){alert("Cannot contain blank"); } else {document. fv. Form. submit(); } } </script> Note: Must use a standard button, not submit button: <input type="button" value="Compute. FVJSP" name="btn. Compute" onclick="Validating()"/>

Check. Box Example A checkbox in a form: <input type="checkbox" name=“NPF" value="ON" /> Non-Profit

Check. Box Example A checkbox in a form: <input type="checkbox" name=“NPF" value="ON" /> Non-Profit In JSP program: my. Chk=request. get. Parameter(“NPF"); if (my. Chk=="ON") out. print("Checkbox is on!"); else out. print(“Checkbox is off!");

Depreciation Table Straight Line Depreciation Table <form name="dep. Form" method="post" action="create. Dep. Table. jsp">

Depreciation Table Straight Line Depreciation Table <form name="dep. Form" method="post" action="create. Dep. Table. jsp"> Enter Property Value: <input type="text" name="p. Value" value="" /> Enter Property Life: <input type="text" name="p. Life" value="" /> <input type="submit" value="Show. Table JSP" name="btn. Show. Table" /> </form>

Output

Output

<% String str. Value, str. Life; str. Value=request. get. Parameter("p. Value"); str. Life=request. get.

<% String str. Value, str. Life; str. Value=request. get. Parameter("p. Value"); str. Life=request. get. Parameter("p. Life"); double value, life, depreciation, total. Depreciation=0; value=Double. parse. Double(str. Value); life=Double. parse. Double(str. Life); depreciation=value/life; Number. Format nf = Number. Format. get. Currency. Instance(); out. print("Stright Line Depreciation Table" + " "); out. print("Property Value: <input type='text' name='p. Value' value='" + nf. format(value) + "' /> "); out. print("Property Life: <input type='text' name='p. Life' value='" + life + "' /> "); total. Depreciation=0; out. print( "<table border='1' width='400' cellspacing=1>"); out. print("<thead> <tr> <th>Year</th> <th>Value at Begin. Yr</th>"); out. print("<th>Dep During Yr</th> <th>Total to End. Of. Yr</th></tr> </thead>"); out. print("<tbody>"); for (int count = 1; count <= life; count++) { out. print("<tr>"); out. print(" <td >" + count + "</td>"); out. print(" <td >" + nf. format(value) + "</td>"); out. print(" <td>" + nf. format(depreciation) + "</td>"); total. Depreciation+=depreciation; out. print(" <td>" + nf. format(total. Depreciation) + "</td>"); value -= depreciation; } %>

Number to Currency Format • Import class: – <%@page import="java. text. Number. Format"%> •

Number to Currency Format • Import class: – <%@page import="java. text. Number. Format"%> • Define a format: – Number. Format nf = Number. Format. get. Currency. Instance(); • Convert: – Example: Display payment with currency format: nf. format(payment)

Using JSP Expression <body> <% String str. Value, str. Life; str. Value=request. get. Parameter("p.

Using JSP Expression <body> <% String str. Value, str. Life; str. Value=request. get. Parameter("p. Value"); str. Life=request. get. Parameter("p. Life"); double value, life, depreciation, total. Depreciation=0; value=Double. parse. Double(str. Value); life=Double. parse. Double(str. Life); Number. Format nf = Number. Format. get. Currency. Instance(); depreciation=value/life; total. Depreciation=depreciation; %> <p>Straight Line Depreciation Table</p> <p>Property Value: <input type='text' name='p. Value' value='<%=nf. format(value)%>' /></p> <p>Property Life: <input type='text' name='p. Life' value='<%=life%>'/></p> <table border='1' width='400' cellspacing=1> <thead> <tr> <th>Year</th> <th>Value at Begin. Yr</th> <th>Dep During Yr</th> <th>Total to End. Of. Yr</th> </tr> </thead> <tbody> <% for (int count = 1; count <= life; count++) { %> <tr> <td><%=count%></td> <td><%=nf. format(value)%></td> <td><%=nf. format(depreciation)%></td> <td><%=nf. format(total. Depreciation)%></td> </tr> <% value -= depreciation; total. Depreciation+=depreciation; } %> </table> </body>

Display Percentage Format: Import class: <%@page import="java. text. Number. Format"%> double rate = 0.

Display Percentage Format: Import class: <%@page import="java. text. Number. Format"%> double rate = 0. 05267; Number. Format p. Format = Number. Format. get. Percent. Instance(); p. Format. set. Minimum. Fraction. Digits(2); out. println("Percent format: " + p. Format. format(rate));

Date to Date Format • Import class: – <%@page import="java. text. Simple. Date. Format"%>

Date to Date Format • Import class: – <%@page import="java. text. Simple. Date. Format"%> – Define a format: • Simple. Date. Format formatter = new Simple. Date. Format("MM/dd/yy"); – Convert: • Example: Display a date with date format: String display. Date = formatter. format(current. Date);

Java Array • Examples of declaring an array: – int[] an. Array = new

Java Array • Examples of declaring an array: – int[] an. Array = new int[10]; • 10 elements index from 0 to 9 – double[] an. Array. Of. Doubles = new double[10]; – String[] an. Array. Of. Strings = new String[10]; – int[] an. Array = { 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};

Creating a listbox of rates double[] rates= {0. 03, 0. 04, 0. 05, 0.

Creating a listbox of rates double[] rates= {0. 03, 0. 04, 0. 05, 0. 06, 0. 07}; String[] displays={"3%", "4%", "5%", "6%", "7%"}; out. println( "Select interest rate: <select name='Rate'>"); for (int i = 0; i <= rates. length-1; i++) { out. print("<option value='" + rates[i] + "'>" + displays[i] + "</option>"); } out. print( "</select> ");

Compute Future Value: Process form with controls Created Using JSP Code: Note this page

Compute Future Value: Process form with controls Created Using JSP Code: Note this page is a jsp page

JSP code to create the form <form name="fv. Form" method="post" action="compute. FV. jsp"> Enter

JSP code to create the form <form name="fv. Form" method="post" action="compute. FV. jsp"> Enter present value: <input type="text" name="PV" value="" /> <% double[] rates= {0. 03, 0. 04, 0. 05, 0. 06, 0. 07}; String[] displays={"3%", "4%", "5%", "6%", "7%"}; out. print( "Select interest rate: <select name='Rate'>"); for (int i = 0; i <= rates. length-1; i++) { out. print("<option value='" + rates[i] + "'>" + displays[i] + "</option>"); } out. print( "</select> "); double[] year. Values= {10, 15, 30}; String[] year. Labels={"10 -year", "15 -year", "30 -year"}; out. print( "Select year: "); for (int i = 0; i <= year. Values. length-1; i++) { out. print("<input type='radio' name='Year' value='" + year. Values[i] + "'/>" + year. Labels[i] + " "); } %> <input type="submit" value="Compute. FVJSP" name="btn. Compute" />

JSP Code to process the form <body> <% String my. PV, my. Rate, my.

JSP Code to process the form <body> <% String my. PV, my. Rate, my. Year; my. PV=request. get. Parameter("PV"); my. Rate=request. get. Parameter("Rate"); my. Year=request. get. Parameter("Year"); double FV, PV, Rate, Year; PV=Double. parse. Double(my. PV); Rate=Double. parse. Double(my. Rate); Year=Double. parse. Double(my. Year); FV=PV*Math. pow(1+Rate, Year); out. print("Future. Value is: "+ FV); %>

Show selected rate and checked radio button checked box: “selected” radiobutton: “checked” <form name="fv.

Show selected rate and checked radio button checked box: “selected” radiobutton: “checked” <form name="fv. Form"> Enter present value: <input type="text" name="PV" value="<%=PV%>" /> <% double[] rates= {0. 03, 0. 04, 0. 05, 0. 06, 0. 07}; String[] displays={"3%", "4%", "5%", "6%", "7%"}; out. print( "Select interest rate: <select name='Rate'>"); for (int i = 0; i <= rates. length-1; i++) { if(rates[i]==Rate) out. print("<option value='" + rates[i] + "' selected>" + displays[i] + "</option>"); else out. print("<option value='" + rates[i] + "'>" + displays[i] + "</option>"); } out. print( "</select> "); double[] year. Values= {10, 15, 30}; String[] year. Labels={"10 -year", "15 -year", "30 -year"}; out. print( "Select year: "); for (int i = 0; i <= year. Values. length-1; i++) { if(year. Values[i]==Year) out. print("<input type='radio' name='Year' value='" + year. Values[i] + "' checked/>" + year. Labels[i] + " "); else out. print("<input type='radio' name='Year' value='" + year. Values[i] + "'/>" + year. Labels[i] + " "); }

Cookie • Cookie is a small data file added by a website to reside

Cookie • Cookie is a small data file added by a website to reside in user’s system. • Define a cookie: – new Cookie(“Key”, “value”); – Ex. Cookie cookie. CID = new Cookie ("cookie. CID", CID); • Write a cookie: – response. add. Cookie(cookie. CID);

Example: <form name="cust. Form" action="add. Cookie. jsp" method="POST"> Enter CID: <input type="text" name="CID" value=""

Example: <form name="cust. Form" action="add. Cookie. jsp" method="POST"> Enter CID: <input type="text" name="CID" value="" /> Enter Cname: <input type="text" name="Cname" value="" /> <input type="submit" value="Add Cookie" name="btn. Submit" /> </form> <% String CID, Cname; CID=request. get. Parameter("CID"); Cname=request. get. Parameter("Cname"); Cookie cookie. CID = new Cookie ("cookie. CID", CID); response. add. Cookie(cookie. CID); Cookie cookie. Cname = new Cookie ("cookie. Cname", Cname); response. add. Cookie(cookie. Cname); out. print("CID cookie= " + CID + "added"); out. print("Cname cookie= " + Cname + "added"); %> Note: To view cookies with Fire. Fox: Tools/Options/Privacy/Remove cookies

Reading Cookies Use request. get. Cookies() method. This method retrieve cookies and return them

Reading Cookies Use request. get. Cookies() method. This method retrieve cookies and return them in an array. <% Cookie[] cookies = request. get. Cookies(); out. print(cookies[0]. get. Name() + cookies[0]. get. Value() + " "); out. print(cookies[1]. get. Name() + cookies[1]. get. Value() + " "); %>

Expire a cookie • Add a expiration time: – cookie. CID set. Max. Age(N);

Expire a cookie • Add a expiration time: – cookie. CID set. Max. Age(N); • N is # of seconds • N = 0, the cookie will be deleted right way • N < 0 : the cookie will be deleted once the user exit the browser Cookie cookie. CID = new Cookie ("cookie. CID", CID); cookie. CID. set. Max. Age(-1);