1 guide to jsp common functions 1.including the libraries as per a java class, e.g. not having to...

33
1 Guide to JSP common functions 1. Including the libraries as per a Java class, e.g. not having to refer to java.util. Date 2. Accessing & using external classes 3. Using JSP to dynamically alter the html displayed 4. Including files 5. Cookies 6. Form processing 7. Session storage for objects 8. Using JavaBeans

Upload: anis-porter

Post on 24-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

1

Guide to JSP common functions

1. Including the libraries as per a Java class, e.g. not having to refer to java.util.Date

2. Accessing & using external classes3. Using JSP to dynamically alter the html

displayed4. Including files5. Cookies6. Form processing7. Session storage for objects8. Using JavaBeans

Page 2: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

2

1. Including libraries

Command:

<%@ page import=“library;" %>

E.g. <%@ page import="java.util.*;" %>

• <%= new java.util.Date() %>

• Note: library needs to be in path known to compiler (i.e. an explicitly defined path) or a path relative to the code

Page 3: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

3

2. Accessing & using external classes

• Means: create an object of the external class and include the class path in the class parameter, i.e. the statement below is equivalent to: jspClass test = new testjsp.jspClass()

<jsp:useBean id="test" scope="session" class="testjsp.jspClass" />

• The class referenced (testjsp) will indicate its membership of a package.

package testjsp;

Page 4: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

4

Example – file jspClass.java

package testjsp;

public class jspClass {public String hello() {return "Hello from jspClass";}public java.util.Date getDate()

{return new Date();}

}

Page 5: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

5

• Type Casting

• String test = 5;

Page 6: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

6

Example – JSP page using an object<%@page contentType="text/html" pageEncoding="UTF-8"%>

<!– Create an object, called ‘test’ from the class type jspClass--><!– The class jspClass is in the package ‘testjsp’--><jsp:useBean id="test" scope="session" class="testjsp.jspClass" />

<html> <head>

<title>JSP Page</title> </head> <body>

<!– Call to object test of class type jspClass --> <%= test.hello() %>Hello from jspClass<%= test.getDate() %></body></html>

Page 7: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

7

3. Using JSP to dynamically alter the html displayed

<% if ("test".equals("test")) { %>

<p> IF statement evaluates to true

<% } else {%>

<p>IF statement evaluates to false

<% } %>

Page 8: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

8

Example – Altering the flow of control<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>If-else-test Page</title> </head> <body> <% if ("test".equals("test")) { %> <p> IF statement evaluates to true<% } else {%> <p>IF statement evaluates to false<% } %> </body></html>

Page 9: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

9

4. Including files

• The <jsp:include> element allows you to include either a static or dynamic file in a JSP file. The results of including static and dynamic files are quite different. If the file is static, its content is included in the calling JSP file. If the file is dynamic, it acts on a request and sends back a result that is included in the JSP page. When the include action is finished, the JSP container continues processing the remainder of the JSP file.

• Beware of infinite loop • You cannot always determine from a pathname if a file is

static or dynamic. For example, http://server:8080/index.html might map to a dynamic servlet through a Web server alias. The <jsp:include> element handles both types of files, so it is convenient to use when you don't know whether the file is static or dynamic.

<above taken from sun notes>

Page 10: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

10

• index.html

• Index.jsp,index.php,default.htm

Myfile.php -> Myfile.jsp

myfile.php

Page 11: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

11

4. Include (example)

<jsp:include page=“terms.html" />

Page 12: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

12

>Request and Response objects (JSP)

• Objects named request and response are generated automatically and can be accessed from the JSP page.

• An object of class type HttpServletRequest is generated (usually named ‘request’)

• An object of type HttpServletResponse is also generated (usually named ‘response’)

• Will need to change the default stream type if you wish to return mime data

response.setContentType(mime-type);e.g.response.setContentType(“video/quicktime-x");

Page 13: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

13

• Import java.servlet.*;

Page 14: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

14

5. Cookies

• Cookies are used for various purposes, for example to track a session, remember a login.

• Cookies are ‘live’ for a preset time on the browser side

• The browser stores the cookie – Possible browser problems: Browser refuses cookies,

browser *should* accept cookie up to a 4kb limit but may not.

• A browser can hold multiple cookies

Page 15: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

15

Cookies - Example<% Cookie authorised = new Cookie("makeCookie", "true"); authorised.setMaxAge(60*60*24*365); response.addCookie(authorised);%>

<%Cookie cookies [] = request.getCookies ();if (cookies != null) for (int i = 0; i < cookies.length; i++) out.println("<br> Cookie is "+cookies [i].getName());<!– NOTE, an object called ‘out’ is automatically created and can be

used for output-->%>

Page 16: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

16

6. Form processing

• Every form should have a name associated with each element, e.g.

<input type="text" name=“tagname"> In JSP the form can be generated from any programming

language (e.g. PHP) or can be static, as long as the form is sent to a JSP page for processing, i.e. the form tag is of the fomat:

<form action= "yourcode.jsp" method= "POST"> • When a form is sent to a JSP page the elements can

be extracted from the request object (it looks after dealing with the data)

<%= request.getParameter(“tagname")%>

Page 17: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

17

Use of forms to maintain sessions

• Form elements can be used to maintain sessions. Example<input type="hidden" name="sessionkey" value=“20"> The key with the value 20 leads to a database record which

contains name, spoken-language, credit card nr, address, etc.

Using forms to store session information also means you can avoid time outs. Dedicated session objects created by the RE have a preset life-span. The user may log in to your application then pause for hours/days. When they return the session object has expired and they have to login again. If the session key was stored as a form element then your programs can keep the user ‘logged in’ forever.

Page 18: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

18

7. Session variables

• To store and access objects in jsp files add the object reference variable and a tag to the session. You will use a method in the session to store the object and tag.

session.setAttribute( "tag-name", object );session.setAttribute( “test", “string” ); Obtain a reference to the object by

extracting it from the session object.session.getAttribute( "test" );

Page 19: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

19

Session variables

• In general wrt the session object - if the value returned is not a fundamental data type OR a String object then you are required to cast the value extracted from a session object to its relevant class after extraction

e.g. (testjsp.jspClass) session.getAttribute( "test" );• Most uses of the session object in JSP pages

will involve objects of type String.

Page 20: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

20

Session Storage Example

<html> <head><title>JSP Page 1 – the form creator</title> </head> <body><!– use the variable called session,which has been automatically

declared and created, to hold a piece of data in a tag called’ this_is_a_tag’ -->

<% session.setAttribute(“this_is_a_tag",“this is data"); %> <h1>Attribute set</h1> <a href="sessionSecondPage.jsp">Second Page</a> </body>

Page 21: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

21

<%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html> <head>

<title>JSP Page 2 – The form processor</title> </head> <body>Value of object stored under tag ' this_is_a_tag ' =<%= session.getAttribute(" this_is_a_tag ") %>

</body></html>

Page 22: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

22

8. JavaBeans

• A Java Bean (code written to a particular standard) can be used to automatically populate an object. This means that you don’t have to use statements like:

<% object.setVariable(request.getParameter(“name”)); %>

i.e. this statement is executed for you, without you having to write any of the set statements.

Page 23: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

23

Important• When using a java bean make sure that the user enters the correct input. If

they don’t insert the correct input, for example if, when entering data into the form component, they enter a String instead of an integer then the RE exits with an error.

• Checking can be done via JSP or JavaScript code (JavaScript sits happily with JSP, the problem with JavaScript is the fact that some browsers block it and some browsers won’t run JavaScript consistent with other browsers. This will not be a problem if you can control the setup of the deployment environment.)

• You can bypass checking if you use only strings and type cast when you want the true value. For example, if I asked for the social security number to be input in the form and I used the following code for the JavaBean that will be processing that form:

private String socialnrString;private int socialnr;public void socialnrString(String stringSupplied) { socialnrString = stringSupplied; socialnr = Integer.parseInt(socialnrString); } // End socialnrString

Page 24: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

24

Using JavaBeans in JSP

• A Java Bean is a Java class that’s written in a particular way.

• One aspect of a Bean is that methods which obtain the value of a variable and alter the value of a variable are written using the words ‘get’ and ‘set’ which is always followed by the name of the variable which has the first letter capitalised.

Page 25: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

25

Example of a basic JavaBean

class beanEg{private int amount; // Note the capital letter in the get and set methodspublic void setAmount(int value){}public int getAmount(){} } // End class beanEg

Page 26: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

26

JSP Forms and Beans

• Can write a class using some of the characteristics of a Bean.

• This will allow form component values to be automatically placed in an object of this class by the VM.

• Conversion to different data types is also done automatically.

Page 27: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

27

Procedure

• Write the HTML form and name the form elements.

• Write the class definition and use same names in the class for variables as was used in the form. Methods which alter and access the elements should be named get and set.

• Write the JSP file and tell VM to setup an object of the class type 

Page 28: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

28

Procedure

• Insert an instruction in the JSP file to tell the VM to call the methods in the object which match the names of the form components supplied.

• The VM automatically inserts values using methods according to names and you are now free to use the relevant object in your JSP page.

Page 29: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

29

Example – Basic JSP

<jsp:useBean id="dataObject" class="dataClass" scope="session"/>

<!– The JSP command below will extract form components from the URL and setup an object with the resulting values -->

<jsp:setProperty name="dataObject" property="*"/>

Page 30: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

30

Example – Class definition

public class dataClass{private String string;private int value;public void setString(String stringSupplied) { string = stringSupplied;} // End setStringpublic String getString() { return string; } // End getStringpublic void setValue(int valueSupplied) { value = valueSupplied; } // End setValuepublic int getValue() { return value; } // End getValue} // End dataClass

Page 31: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

31

Tag Libraries

• Custom JSP tags available if JSP is run on specific web server 

• Tag libraries generally offer useful features which allow rapid development of JSP pages, like simplified database access.

Page 32: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

32

Other relevant JSP notes

Page 33: 1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external

33

JSP Execution

• JSP pages are actually executed as servlets. 

• When a JSP engine receives a JSP page it creates a standard servlet from a template and inserts the embedded code into this servlet. It then executes the servlet and replaces the JSP code with the results.