Server-Side Scripting with Java Server Page, JSP

Slides:



Advertisements
Similar presentations
HTML Forms. collect information for passing to server- side processes built up from standard widgets –text-input, radio buttons, check boxes, option lists,
Advertisements

Java Classes ISYS 350. Introduction to Classes A class is the blueprint for an object. – It describes a particular type of object. – It specifies the.
Video, audio, embed, iframe, HTML Form
Server-Side Scripting with Java Server Page, JSP.
JavaScript Forms Form Validation Cookies CGI Programs.
Forms Review. 2 Using Forms tag  Contains the form elements on a web page  Container tag tag  Configures a variety of form elements including text.
USER INTERACTIONS: FORMS
Java Servlet. What is Java Servlet? A Servlet is a java based server side web technology. It is a java class that serves a client request and receives.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
Comp2513 Forms and CGI Server Applications Daniel L. Silver, Ph.D.
AJAX and Java ISYS 350. AJAX Asynchronous JavaScript and XML: – Related technologies: JavaScript, Document Object Model, XML, server-side script such.
Server-Side Scripting with JSP (2) ISYS 350. Java Array Examples of declaring an array: – int[] anArray = new int[10]; 10 elements index from 0 to 9 –
Server-Side Scripting with Java Server Page, JSP ISYS 350.
CSC 2720 Building Web Applications HTML Forms. Introduction  HTML forms are used to collect user input.  The collected input is typically sent to a.
Server-Side Scripting with Java Server Page, JSP ISYS 350.
Chapter 8 Cookies And Security JavaScript, Third Edition.
Java Classes ISYS 350. Introduction to Classes Two basic uses of class: – 1. A class is a way to organize functions (methods) to perform calculations.
Website Development with PHP and MySQL Saving Data.
1 © Netskills Quality Internet Training, University of Newcastle HTML Forms © Netskills, Quality Internet Training, University of Newcastle Netskills is.
CSC 2720 Building Web Applications Server-side Scripting with PHP.
Web App GUI: JSP Basics & Forms 3680 Enterprise Programming.
Jsp (Java Server Page) Is a server side program.
Server-Side Scripting with JSP (2) ISYS 350. Post Back A postback is call to the same page that the form is on. In other words, the contents of the form.
Server-Side Scripting with PHP ISYS 475. PHP Manual Website
Server-Side Scripting with JSP (2) ISYS 350. Java Array Examples of declaring an array: – int[] anArray = new int[10]; 10 elements index from 0 to 9 –
Java Servlet ISYS 350. What is Java Servlet? It is a java class that serves a client request. Servlets are most often used to: Process or store data that.
©SoftMooreSlide 1 Introduction to HTML: Forms ©SoftMooreSlide 2 Forms Forms provide a simple mechanism for collecting user data and submitting it to.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
1 State and Session Management HTTP is a stateless protocol – it has no memory of prior connections and cannot distinguish one request from another. The.
Server-Side Scripting with Java Server Page, JSP.
Server-Side Scripting with Java Server Page, JSP ISYS 350.
Server-Side Scripting with Java Server Page, JSP ISYS 350.
HTML III (Forms) Robin Burke ECT 270. Outline Where we are in this class Web applications HTML Forms Break Forms lab.
Lesson 5 Introduction to HTML Forms. Lesson 5 Forms A form is an area that can contain form elements. Form elements are elements that allow the user to.
HTML Structure II (Form) WEEK 2.2. Contents Table Form.
Advanced HTML Tags:.
JSP java server pages.
Working with Date ISYS 350.
Java Class and Servlet ISYS 350.
Computing with C# and the .NET Framework
How to Write Web Forms By Mimi Opkins.
CS3220 Web and Internet Programming HTML Tables and Forms
In this session, you will learn about:
Java String and Date ISYS 350.
AJAX and Java Servlet ISYS 350.
Basic XHTML Tables XHTML tables—a frequently used feature that organizes data into rows and columns. Tables are defined with the table element. Table.
JSP Implicit Objects Implicit Objects in JSP are objects that are automatically available in JSP. request: The request object retrieves the values that.
Web Programming– UFCFB Lecture 17
PHP Overview PHP: Hypertext Preprocessor Server-Side Scripting
Java Date ISYS 350.
Introducing Forms.
HTML: Basic Tags & Form Tags
Server-Side Scripting with Java Server Page, JSP
AJAX and JSP ISYS 350.
The Request & Response object
Database Processing with JSP
Servlets.
Java Server Pages.
Client side & Server side scripting
FORM OBJECT When creating an interactive web site for the Internet it is necessary to capture user input and process this input. Based on the result of.
Forms, cont’d.
Java Date ISYS 350.
Java Servlet ISYS 350.
Lecture 5: Functions and Parameters
HTML Forms 18-Apr-19.
Java Date ISYS 350.
AJAX and JSP ISYS 350.
PHP-II.
Java Date ISYS 350.
HTML: Basic Tags & Form Tags
Presentation transcript:

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

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

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.

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

Use JSP to Process a Form

FORM Button: Form attribute: Type = “submit” 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 QueryString. Post: A preferred method for database processing. Form’s data is sent in the HTTP body. Post is the preferred method. Example: <form name="testForm" method="post" action="computeSum.jsp“> Button: Type = “submit” <input type="submit" value="ComputeSumJSP" name="btnCompute"/>

QueryString A QueryString 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 QueryString: Add a question mark (?) immediately after a URL. Followed by name=value pairs separated by ampersands (&). Example: <A Href=“http://my.com/Target.htm?CustID=C1&Cname=Chao”>

Data Sent with Request and Response requested URL, cookies, queryString, 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 you mix regular, static HTML with dynamically-generated 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 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.

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.

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> <h1>Hello World!</h1> <% out.print("Welcome!!!"); out.print("To JSP Training"); %> </body> Question: How to start a new line? out.print("<br>To JSP Training");

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:

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> Notre 1: The form has a method property nd action property. Note2: The button now is type: submit, and there is no onclick event.

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.print("The sum is:" + sum); %> </body> Note 1: Double is an object that offers the parseDouble method, not “double” data type. Note 2: “out” is an implicit object that does not need to be declared.  It is already predefined .

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.print(" <p>Value1: <input type=‘text' name='num1' size='20' value='" + value1 + "'></p>"); out.print(" <p>Value2: <input type='text' name='num2' size='20' value='" + value2 + "'></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 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" > <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>

Compute Future Value: Process form with various controls

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>

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.print("FutureValue is:"+ FV); %>

CheckBox Example: value attribute A checkbox in a form: <input type="checkbox" name=“NPF" value="ON" /> Non-Profit In JSP program: myChk=request.getParameter(“NPF"); if (myChk=="ON") out.print("Checkbox is on!"); else out.print(“Checkbox is off!");

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>

Output

<% 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); depreciation=value/life; NumberFormat nf = NumberFormat.getCurrencyInstance(); out.print("Stright Line Depreciation Table" + "<br>"); out.print("Property Value: <input type='text' name='pValue' value='" + nf.format(value) + "' /><br>"); out.print("Property Life: <input type='text' name='pLife' value='" + life + "' /><br>"); totalDepreciation=0; out.print( "<table border='1' width='400' cellspacing=1>"); out.print("<thead> <tr> <th>Year</th> <th>Value at BeginYr</th>"); out.print("<th>Dep During Yr</th> <th>Total to EndOfYr</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>"); totalDepreciation+=depreciation; out.print(" <td>" + nf.format(totalDepreciation) + "</td>"); value -= depreciation; } %>

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

Using JSP Expression <body> <% 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(); depreciation=value/life; totalDepreciation=depreciation; %> <p>Straight Line Depreciation Table</p> <p>Property Value: <input type='text' name='pValue' value='<%=nf.format(value)%>' /></p> <p>Property Life: <input type='text' name='pLife' value='<%=life%>'/></p> <table border='1' width='400' cellspacing=1> <thead> <tr> <th>Year</th> <th>Value at BeginYr</th> <th>Dep During Yr</th> <th>Total to EndOfYr</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(totalDepreciation)%></td> </tr> value -= depreciation; totalDepreciation+=depreciation; } </table> </body>

Display Percentage Format: Import class: <%@page import="java. text Display Percentage Format: Import class: <%@page import="java.text.NumberFormat"%> double rate = 0.05267; NumberFormat pFormat = NumberFormat.getPercentInstance(); pFormat.setMinimumFractionDigits(2); out.println("Percent format: " + pFormat.format(rate));

Use Client-Side Validating and Sumbit Validated Form <script > 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()"/>

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

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

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

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

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><br><br>");

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="fvForm" method="post" action="computeFV.jsp"> Enter present value: <input type="text" name="PV" value="" /><br><br> <% 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><br><br>"); double[] yearValues= {10,15,30}; String[] yearLabels={"10-year","15-year","30-year"}; out.print( "Select year:<br><br>"); for (int i = 0; i <= yearValues.length-1; i++) out.print("<input type='radio' name='Year' value='" + yearValues[i] + "'/>" + yearLabels[i] + "<br><br>"); %> <input type="submit" value="ComputeFVJSP" name="btnCompute" /> </form>

JSP Code to process the form <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.print("FutureValue is:"+ FV); %>

Show selected rate and checked radio button checked box: “selected” radiobutton: “checked” <form name="fvForm"> Enter present value: <input type="text" name="PV" value="<%=PV%>" /><br><br> <% 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><br><br>"); double[] yearValues= {10,15,30}; String[] yearLabels={"10-year","15-year","30-year"}; out.print( "Select year:<br><br>"); for (int i = 0; i <= yearValues.length-1; i++) if(yearValues[i]==Year) out.print("<input type='radio' name='Year' value='" + yearValues[i] + "' checked/>" + yearLabels[i] + "<br><br>"); out.print("<input type='radio' name='Year' value='" + yearValues[i] + "'/>" + yearLabels[i] + "<br><br>"); %> FV: <input type="text" name="FV" value="<%=FV%>" /><br><br> <input type="submit" value="ComputeFVJSP" name="btnCompute" /> </form>

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);

Example: </form> <% String CID, Cname; <form name="custForm" action="addCookie.jsp" method="POST"> Enter CID: <input type="text" name="CID" value="" /><br><br> Enter Cname: <input type="text" name="Cname" value="" /><br><br> <input type="submit" value="Add Cookie" name="btnSubmit" /> </form> <% 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.print("CID cookie= " + CID + "added"); out.print("Cname cookie= " + Cname + "added"); %> Note: To view cookies with FireFox:Tools/Options/Privacy/Remove cookies

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

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);