330 likes | 386 Views
Guide to JSP common functions. Including the libraries as per a Java class, e.g. not having to refer to java.util. Date Accessing & using external classes Using JSP to dynamically alter the html displayed Including files Cookies Form processing Session storage for objects Using JavaBeans.
E N D
Guide to JSP common functions • Including the libraries as per a Java class, e.g. not having to refer to java.util.Date • Accessing & using external classes • Using JSP to dynamically alter the html displayed • Including files • Cookies • Form processing • Session storage for objects • Using JavaBeans
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
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;
Example – file jspClass.java package testjsp; public class jspClass { public String hello() {return "Hello from jspClass";} public java.util.Date getDate() {return new Date();} }
Type Casting • String test = 5;
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>
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 <% } %>
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>
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>
index.html • Index.jsp,index.php,default.htm Myfile.php -> Myfile.jsp myfile.php
4. Include (example) <jsp:include page=“terms.html" />
>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");
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
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--> %>
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")%>
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.
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" );
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.
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 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>
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.
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
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.
Example of a basic JavaBean class beanEg { private int amount; // Note the capital letter in the get and set methods public void setAmount(int value) {} public int getAmount() {} } // End class beanEg
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.
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
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.
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="*"/>
Example – Class definition public class dataClass { private String string; private int value; public void setString(String stringSupplied) { string = stringSupplied;} // End setString public String getString() { return string; } // End getString public void setValue(int valueSupplied) { value = valueSupplied; } // End setValue public int getValue() { return value; } // End getValue } // End dataClass
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.
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.