Server-Side Scripting with Java Server Page, JSP

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

description

Server-Side Scripting with Java Server Page, JSP. ISYS 350. Java Website. Java Tutorial: http://docs.oracle.com/javase/tutorial/ JSP, Servlet tutorial: http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/. Java Platforms. - PowerPoint PPT Presentation

Transcript of Server-Side Scripting with Java Server Page, JSP

Page 1: Server-Side Scripting with Java Server Page, JSP

Server-Side Scripting with Java Server Page, JSP

ISYS 350

Page 2: Server-Side Scripting with Java Server Page, JSP

Java Website

• Java Tutorial:– http://docs.oracle.com/javase/tutorial/

• JSP, Servlet tutorial:– http://www.apl.jhu.edu/~hall/java/Servlet-Tutoria

l/

Page 3: Server-Side Scripting with Java Server Page, JSP

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, multi-tiered, 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.

Page 4: Server-Side Scripting with Java Server Page, JSP

Using Java Classes

• To develop Java applications, we need to use many different Java classes.

• Groups of related Java classes are organized into packages.

• To use a class from a package we use the “import” statement to import the class.

Page 5: Server-Side Scripting with Java Server Page, JSP

Common Java packages

Package name Description

java.lang Provides classes fundamental to Java, including classes that work with primitive data types, strings, and math functions.

java.text Provides classes to handle text, dates, and numbers.

java.util Provides various utility classes including those for working with collections.

java.io Provides classes to read data from files and to write data to files.

java.sql Provides classes to read data from databases and to write data to databases.

java.applet An older package that provides classes to create an applet.

Page 6: Server-Side Scripting with Java Server Page, JSP

Common Java packages (continued)

Package name Description

java.awt An older package called the Abstract Window Toolkit (AWT) that provides classes to create graphical user interfaces.

java.awt.event A package that provides classes necessary to handle events.

javax.swing A newer package called Swing that provides classes to create graphical user interfaces and applets.

Page 7: Server-Side Scripting with Java Server Page, JSP

Hyper Text Transfer Protocol: Request & Response

Web ServerBrowser

HTTP Request

HTTP Response

Web Application

Page 8: Server-Side Scripting with Java Server Page, JSP

Data Sent with Request and Response

• Request: – requested URL, cookies, queryString, data from a

form, etc.

• Response:– Web page content in HTML code– Cookies– Etc.

Page 9: Server-Side Scripting with Java Server Page, JSP

JSP Implicit Objects• Implicit Objects in JSP are objects that are

automatically available in JSP. Implicit Objects are Java objects that the JSP Container provides to a developer to access them in their program.– request: The request object retrieves the values that the client

browser passed to the server during an HTTP request

– response: 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

Page 10: Server-Side Scripting with Java Server Page, JSP

Methods of request Objecthttp://gulland.com/courses/jsp/objects

• getParameter(String name): Returns the value of a request parameter as a String, or null if the parameter does not exist.

• getQueryString(): Gets any query string that is part of the HTTP request URI.

• getCookies(): Gets the array of cookies found in this request.

• getRequestURI(): Gets the URI to the current JSP page.

• etc.

Page 11: Server-Side Scripting with Java Server Page, JSP

Methods of response Object

• addCookie(Cookie): Adds the specified cookie to the response. It can be called multiple times to set more than one cookie.

• sendRedirect(String): Sends a temporary redirect response to the client using the specified redirect location URL.

Page 12: Server-Side Scripting with Java Server Page, JSP

JSP Out Object• clearBuffer: The clearBuffer method of out

object is used to clear the output buffer. • println: The println method of out object is used

to write the value to the output, including the newline character. – Ex. out.println("The Output is:" + ex);

• 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

Page 13: Server-Side Scripting with Java Server Page, JSP

Use JSP to Process a Form

Page 14: Server-Side Scripting with Java Server Page, JSP

FORM

• Form attribute:– Method:

• Preferred method is: Post– 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<form name="testForm" method="post" action="computeSum.jsp“>

• Button:– Type = “submit”

<input type="submit" value="ComputeSumJSP" name="btnCompute"/>

Page 15: Server-Side Scripting with Java Server Page, JSP

The eight primitive data types

Type Bytes Use

byte 1 Very short integers from -128 to 127.

short 2 Short integers from -32,768 to 32,767.

int 4 Integers from -2,147,483,648 to 2,147,483,647.

long 8 Long integers from -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807.

float 4 Single-precision, floating-point numbers from -3.4E38 to 3.4E38 with up to 7 significant digits.

double 8 Double-precision, floating-point numbers from -1.7E308 to 1.7E308 with up to 16 significant digits.

char 2 A single Unicode character that’s stored in two bytes.

boolean 1 A true or false value.

Page 16: Server-Side Scripting with Java Server Page, JSP

Compute the Sum of 2 Numbers:

Page 17: Server-Side Scripting with Java Server Page, JSP

Form Example

<body> <div>Compute the sum of two numbers</div> <form name="testForm" method="post" action="computeSum.jsp"> Enter num1: <input type="text" name="num1" value="" /><br> Enter num2: <input type="text" name="num2" value="" /><br><br> <input type="submit" value="ComputeSumJSP" name="btnCompute"/> </form> </body>

Page 18: Server-Side Scripting with Java Server Page, JSP

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

<body> <% String value1, value2; double n1, n2, sum; value1=request.getParameter("num1"); value2=request.getParameter("num2"); n1= Double.parseDouble(value1); n2= Double.parseDouble(value2); sum=n1+n2; out.println("The sum is:" + sum); %> </body>

Note 1: Double is an object, not “double” data type.Note 2: “out” is an implicit object that does not need to be declared. It is already predefined .

Page 19: Server-Side Scripting with Java Server Page, JSP

Writing HTML code as output<body> <% String value1, value2; double n1, n2, sum; value1=request.getParameter("num1"); value2=request.getParameter("num2"); n1= Double.parseDouble(value1); n2= Double.parseDouble(value2); sum=n1+n2; out.println(" <p>Value1: <input type='text' name='num1' size='20' value='" + value1 + "'></p>"); out.println(" <p>Value2: <input type='text' name='num2' size='20' value='" + value2 + "'></p>");

out.println("The sum is: <input type='text' name='sum' size='20' value='" + sum + "'>" ); %> </body>

Page 20: Server-Side Scripting with Java Server Page, JSP

Using JSP Expression:return a string, <%= %>

String value1, value2; double n1, n2, sum; value1=request.getParameter("num1"); value2=request.getParameter("num2"); n1= Double.parseDouble(value1); n2= Double.parseDouble(value2); sum=n1+n2; %>

<form method="POST" name="testForm" action="ComputeSum2.jsp"> <p>Value1: <input type="text" name="num1" size="20" value="<%=value1%>"></p> <p>Value2: <input type="text" name="num2" size="20" value="<%=value2%>"></p> <p> Sum is: <input type="text" name="num2" size="20" value="<%=sum%>"></p></form>

Page 21: Server-Side Scripting with Java Server Page, JSP

Import Java ClassExample: Display Current Date Time

• Import java.util.Date– %@page import="java.util.Date"%

• Define a Date type variable:– Date now = new Date();

• Display in textbox using JSP expression:<p>The time is: <input type="text" name="num2" size="20" value="<

%=now%>"></p>

Page 22: Server-Side Scripting with Java Server Page, JSP

Compute Future Value:Process form with various controls

Page 23: Server-Side Scripting with Java Server Page, JSP

Form Code<form name="fvForm" method="post" action="computeFV.jsp"> Enter present value: <input type="text" name="PV" value="" /><br><br> 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><br><br> Select year: <br> <input type="radio" name="Year" value="10" />10-year<br> <input type="radio" name="Year" value="15" />15-year<br> <input type="radio" name="Year" value="30" />30-year<br><br>

<input type="submit" value="ComputeFVJSP" name="btnCompute" /> </form>

Page 24: Server-Side Scripting with Java Server Page, JSP

JSP Code Example

<body> <% String myPV, myRate, myYear; myPV=request.getParameter("PV"); myRate=request.getParameter("Rate"); myYear=request.getParameter("Year"); double FV, PV, Rate, Year; PV=Double.parseDouble(myPV); Rate=Double.parseDouble(myRate); Year=Double.parseDouble(myYear); FV=PV*Math.pow(1+Rate,Year); out.println("FutureValue is:"+ FV); %>

Page 25: Server-Side Scripting with Java Server Page, JSP

Using the get method

• Querystring:– http://localhost:8080/DemoM262/computeFVget.jsp?PV=

1000&Rate=.04&Year=10&btnCompute=ComputeFVJSP

• Code:String qString;qString=request.getQueryString();out.println(qString);

Page 26: Server-Side Scripting with Java Server Page, JSP

Use the same getParameter() method to accessing data submitted with a querystring

<body> <% String myPV, myRate, myYear; myPV=request.getParameter("PV"); myRate=request.getParameter("Rate"); myYear=request.getParameter("Year"); double FV, PV, Rate, Year; PV=Double.parseDouble(myPV); Rate=Double.parseDouble(myRate); Year=Double.parseDouble(myYear); FV=PV*Math.pow(1+Rate,Year); out.println("FutureValue is:"+ FV); %>

Page 27: Server-Side Scripting with Java Server Page, JSP

Use Client-Side Validating and Sumbit Validated Form

<script type="text/javascript"><!--function Validating(){var Valid;Valid=true;if (document.fvForm.PV.value=="") {Valid=false;}

if (Valid==false){alert("Cannot contain blank");}else {document.fvForm.submit();}

}--></script>

Note: Must use a standard button, not submit button: <input type="button" value="ComputeFVJSP" name="btnCompute" onclick="Validating()"/>

Page 28: Server-Side Scripting with Java Server Page, JSP

Depreciation Table

Straight Line Depreciation Table <form name="depForm" method="post" action="createDepTable.jsp"> Enter Property Value: <input type="text" name="pValue" value="" /><br> Enter Property Life: <input type="text" name="pLife" value="" /><br> <input type="submit" value="ShowTable JSP" name="btnShowTable" /> </form>

Page 29: Server-Side Scripting with Java Server Page, JSP

Output

Page 30: Server-Side Scripting with Java Server Page, JSP

<% String strValue, strLife; strValue=request.getParameter("pValue"); strLife=request.getParameter("pLife"); double value, life, depreciation,totalDepreciation=0; value=Double.parseDouble(strValue); life=Double.parseDouble(strLife); NumberFormat nf = NumberFormat.getCurrencyInstance(); out.println("Straight Line Depreciation Table" + "<br>"); out.println("Property Value: <input type='text' name='pValue' value='" + nf.format(value) + "' /><br>"); out.println("Property Life: <input type='text' name='pLife' value='" + life + "' /><br>"); depreciation=value/life; totalDepreciation=depreciation; out.println( "<table border='1' width='400' cellspacing=1>"); out.println("<thead> <tr> <th>Year</th> <th>Value at BeginYr</th>"); out.println("<th>Dep During Yr</th> <th>Total to EndOfYr</th></tr> </thead>"); out.println("<tbody>"); for (int count = 1; count <= life; count++) { out.write("<tr>"); out.write(" <td width='25%'>" + count + "</td>"); out.write(" <td width='25%'>" + nf.format(value) + "</td>"); out.write(" <td width='25%'>" + nf.format(depreciation) + "</td>"); out.write(" <td width='25%'>" + nf.format(totalDepreciation) + "</td>"); value -= depreciation; totalDepreciation+=depreciation; } %>

Page 31: Server-Side Scripting with Java Server Page, JSP

Number to Currency Format

• Import class:– %@page import="java.text.NumberFormat"%

• Define a format:– NumberFormat nf = NumberFormat.getCurrencyInstance();

• Convert:– nf.format(value)

Page 32: Server-Side Scripting with Java Server Page, JSP

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 cookieCID = new Cookie ("cookieCID",CID);

• Write a cookie: – response.addCookie(cookieCID);

Page 33: Server-Side Scripting with Java Server Page, JSP

Example:

<% String CID, Cname; CID=request.getParameter("CID"); Cname=request.getParameter("Cname"); Cookie cookieCID = new Cookie ("cookieCID",CID); response.addCookie(cookieCID); Cookie cookieCname = new Cookie ("cookieCname",Cname); response.addCookie(cookieCname);

out.println("CID cookie= " + CID + "added"); out.println("Cname cookie= " + Cname + "added"); %>

Page 34: Server-Side Scripting with Java Server Page, JSP

Read Cookies:Cookie is in array object, we need to get in

request.getCookies() of array

<% Cookie[] cookies = request.getCookies(); out.println(cookies[0].getName() + cookies[0].getValue() + "<br>"); out.println(cookies[1].getName() + cookies[1].getValue() + "<br>"); %>

Page 35: Server-Side Scripting with Java Server Page, JSP

Expire a cookie

• Add a expiration time:– cookieCID setMaxAge(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 cookieCID = new Cookie ("cookieCID",CID);cookieCID setMaxAge(-1);

Page 36: Server-Side Scripting with Java Server Page, JSP

JSP Session Object• Session Object denotes the data associated

with a specific session of user. • Methods:

– session.setAttribute(“Key”, object)• add an object to the session object associated with a key.

– session.getId()• return the unique identifier associated with the session

– session.getAttribute(“key”)• return the object with the specified key given in

parameter

Page 37: Server-Side Scripting with Java Server Page, JSP

Add an object to session objectAdd Cname to session, then redirect to another page to

read the cname

<% Cookie[] cookies = request.getCookies(); out.println(cookies[0].getName() + cookies[0].getValue() + "<br>"); out.println(cookies[1].getName() + cookies[1].getValue() + "<br>"); session.setAttribute("Cname", cookies[1].getValue()); response.sendRedirect("readSession.jsp"); %>

Page 38: Server-Side Scripting with Java Server Page, JSP

Retrieve an object from session

<% Object custName; custName=session.getAttribute("Cname"); out.println("Welcome, " + custName.toString()); %>