Jsp

  • Uploaded by: mohanraop
  • 0
  • 0
  • May 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Jsp as PDF for free.

More details

  • Words: 9,887
  • Pages: 203
Programming

1

Understanding •Java Server Pages isJSP another technology

defined by Sun Microsystems to generate dynamic web content. •JSP is a form of server-side applications. •They are direct extension of servlets. •They are more efficient than servlets. •JSP is a type of server-side scripting language. •JSP program files have an extension .jsp 2

Understanding JSP which are They are HTML documents



embedded with Java code using different JSP tags. When compared with servlets they are unstructured and contains pieces of java code scattered through out an HTML file.



Since they are server-side applications, they have access to server resources such as servlets, javabeans, Ejbs and databases. 3



Advantages of JSP they allow •JSP’s being Java programs, write-once, run-anywhere policy. •JSP tags are simple to understand, since they are similar to HTML and XML. •Since there is a standard, published API for JSP, and because of Java code portability, use of JSP is independent of hardware, OS or server software.

4



Advantages of JSP JSP being vendor-neutral, developers and system architects can select best-of-breed solutions at all stages of JSP deployment.



It has full access to the underlying J2SE APIs (database access, directory services, distributed computing, cryptography…).



Hence JSP is highly flexible and featurerich to create web-based applications.

5



Advantages of JSP Does not require server restart when the JSP program code changes.



Separation of roles into graphical content and dynamic content.



JSP’s being a modified way of writing servlets, they can provide all features/capabilities of a servlets.

6



JSP History Servlets first appeared as part of Sun’s Java Web Server (JWS), a Java based HTTP server in 1997.



Sun eventually released the Servlet technology as a standard Java extension.



JSP soon followed, with the first draft API specifications appearing in 1998. 7

JSP History 

JSP 1.0 Specification was released in June 1999 as a part of J2EE.



JSP 1.1 - Late 1999.



JSP 1.2 - 2001.



JSP 2.0 – 2003. 8



Third party vendor support RAD tools are now available to create dynamic web pages, using DnD approach.



Ability to create sophisticated JSP pages without seeing HTML tags, let alone Java code will enhance the productivity to a greater extent.



Ex: Drumbeat 2000 from Macromedia IBM’s Visual Age for Java HomeSite from Allaire

9

JSP vs ASP Features Asp

Jsp

WEB Server

IIS, PWS

Many

Platform

Windows Any

Reusable components

Com

Javabeans/EJB

Memory leak protection Scripting languages

No

Yes

Security

J-script, Java VB-script No yes

Customized tags

No

yes 10



JSP vs JavaScriptJavaScript 

Validates on Client Side



Browser Dependent



Unstable



Interpreted



Server-side JavaScript is dependent on proprietary servers. 11

JSP vs Servlets 

Similarities 

Provides identical results to end user.



JSP is an extension of servlets.



Provides similar API support. 12



JSP vs Servlets

Differences 

Servlets: “HTML embedded in Java Code” HTML code inaccessible to Graphics designer But accessible to Programmer.



JSP: “Java Code embedded in HTML” HTML code accessible to Graphic Designer Java code accessible to Programmer.



Jsp allows code update without restarting the server.



Eliminates redundant code.

13

Comparing servlet and JSP code

1. import java.io.*; 2. import javax.servlet.*; 3. import javax.servlet.http.*;

5. public class HelloWorld extends HttpServlet 6. { 7. public void doGet(HttpServletRequest req, HttpServletResponse res) 8. throws ServletException, IOException 9. { 10. res.setContentType("text/html"); 11. PrintWriter out = res.getWriter(); 12. out.println(""); 13. out.println("<TITLE>Hello World"); 14. out.println(""); 15. out.println("Hello World"); 16. out.println(""); 17. } 18. } 14

Comparing servlet and JSP code 1. 2. <TITLE>Hello World 3. 4.

Hello World

5. 6.

Note: HTML content is also valid JSP content, since JSP is HTML code embedded with java code. 15

JSP functionality architecture Web Server JSP Page est u q Re

Translation by JSP engine Generated Servlet

Web Client

Compilation Re

sp

on

se

Compiled Servlet Instantiation Servlet is loaded to server 16

JSP functionality architecture

17

  

JSP life cycle

jspInit() jspDestroy() _jspService( request, response ) jspInit() Initialise JSP Invoked only once

_jspService(request,response) Handle Requests: invoked for every request

jspDestroy() Invoked by container to cleanup

•Implementation of these methods are generated by the Container and not by JSP authors. 18



JSP and the JSP Engine Contract between the JSP engine and JSP 

jspInit() Corresponds to servlet init(), but has no parameters (use config implicit object to obtain information regarding environment).



jspService() The main processing method; all Java code belongs to this method by default (if not contained in another method), but it is not explicitly declared in a JSP document.



jspDestroy() Corresponds to the servlet destroy() method and is called just before the generated servlet is destroyed. 19

Package java.servlet.jsp Interface Hierarchy

Class Hierarchy 20

Interface javax.servlet.Servlet

•Top most in the servlet API hierarchy. •It is implemented by javax.servlet.GenericServlet, which is further extended by javax.servlet.http.HttpServlet. •public void init(ServletConfig config) •public void service( ServletRequest req, ServletResponse res) •public void destroy() •public ServletConfig getServletConfig() •public String getServletInfo()

21



Interface JspPage It describes the generic interaction that a JSP

Page implementation class must satisfy.  Pages that use HTTP protocol are described by HttpJspPage interface. 





public void jspInit() Invoked when the JSP page is initialized. public void jspDestroy() Invoked before destroying the JSP page.

Note: The jspInit() and jspDestroy() can be defined by a JSP author, but _jspService() is defined automatically by the JSP processor based on contents of the JSP page. 22





Interface HttpJspPage Extends JspPage and describes interaction

that a JSP Page implementation class must satisfy when using HTTP protocol. Behaviour is identical to JspPage, except that _jspService method is now expressible in Java type system optimized for HTTP. 

void _jspService( HttpServletRequest request, HttpServletResponse response) It corresponds to body of the JSP page.  It is defined automatically by the JSP container. 

23

Class JspFactory

Defines factory methods available to a JSP page at runtime to enable instantiation of implementation-dependent PageContext and JspEngineInfo that support JSP implementation. JSP Engine, during it's startup instantiates an implementation dependent subclass of this class. This instance is made globally available by registering it using setDefaultFactory() method. Note: JspFactory objects should not be used by JSP page authors. 24 

   



Class JspFactory

static static abstract abstract

void setDefaultFactory(JspFactory deflt) JspFactory getDefaultFactory() JspEngineInfo getEngineInfo() PageContext getPageContext( Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int buffer, boolean autoflush)  Instantiates an implementation dependent PageContext for the calling Servlet. abstract void releasePageContext(PageContext pc)25

Class JspEngineInfo 

Provides information about the current JSP engine (container).



abstract String getSpecificationVersion() Return version of the JSP specification supported by this JSP engine. May return null, if version details is not known. 26

Class PageContext 

Provides access to JSP implicit objects and page attributes.



It is an abstract class, and is implemented by container provider.



It is instantiated using static method getPageContext() and is released using releasePageContext() of JspFactory. 27

Field Summary

static String APPLICATION Name used to store ServletContext in PageContext name table.  static String CONFIG Name used to store ServletConfig.  static String EXCEPTION Name used for uncaught exception.  static String OUT Name used to store current JspWriter.  static String PAGE Name used to store the Servlet.  static String PAGECONTEXT 28 Name used to store this PageContext. 

Field Summary…

static String REQUEST Name used to store ServletRequest.  static String RESPONSE Name used to store ServletResponse.  static String SESSION Name used to store HttpSession. 

   

static int PAGE_SCOPE static int REQUEST_SCOPE static int SESSION_SCOPE static int APPLICATION_SCOPE

Indicates scope of a bean reference. 29



















Method Summary The following methods provide convenient

access to implicit objects: abstract JspWriter getOut() Returns current value of the out object (JspWriter). abstract Object getPage() abstract ServletRequest getRequest() abstract ServletResponse getResponse() abstract ServletConfig getServletConfig() abstract ServletContext getServletContext() abstract HttpSession getSession() abstract Exception getException() 30



Method Summary Object findAttribute( String name)

Search and return attribute value (or null) in scope sequence of page, request, session and application.  Object getAttribute( String name) Return attribute value of name in page scope.  Enumeration getAttributeNamesInScope(int scope)  abstract int getAttributesScope( String name)  void removeAttribute( String name) Search for attribute in scope order and remove it.  void removeAttribute( String name, int scope)  void setAttribute( String name, Object value) Register attribute in page scope.  void setAttribute( String name, Object v, int scope) 31



Method Summary abstract void forward( String relativeUrlPath)

Re-directs/forwards current Request and Response to another component.  abstract void include( String relativeUrlPath) Inserts content/output of refered component.  abstract void handlePageException ( Exception e) Redirects exception to the specified error page (if available) or to default handler.  abstract void handlePageException ( Throwable t ) 32



Method Summary abstract void initialize(Servlet ser,

ServletRequest req, ServletResponse res, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush) Initializes PageContext to be used by a JSP to service an incoming request. abstract void release() It resets PageContext state, releasing internal 

references and preparing PageContext for reuse by a later invocation of initialize().

33

Method Summary

Following methods enable management of JspWriter streams to implement Tag Extensions: 

JspWriter popBody()

Returns JspWriter saved by the matching pushBody(), and updates value of "out“ attribute in page scope of the PageConxtext. 

BodyContent pushBody()

Returns a new BodyContent object, and updates the value of "out“ attribute in the page scope attribute namespace of the PageContext. 34

  

  

Class JspWriter

Provides output stream for JSP's. It extends java.io.Writer. A JSPWriter object is available within JSP as implicit object out, which is initialized automatically using methods of PageContext object. abstract abstract abstract

 

abstract

 

abstract

void void void int int boolean void

clearBuffer() close() flush() getBufferSize() getRemaining() isAutoFlush() newLine()

35

Class JspWriter… void println() void print(boolean b) void print(char c) void print(char[] s) void print(double d) void print(float f) void print(int i) void print(long l) void print(Object obj) void print(String s)

void void void void void void void void void

println(boolean x) println(char x) println(char[] x) println(double x) println(float x) println(int x) println(long x) println(Object x) println(String x)

36



Tag convention JSP tags usage is similar to those of HTML tags:  They begin and end with angle brackets.



JSP tags fall into 2 basic categories:  Scripting-oriented tags inspired by ASP.  Tags based on XML style. 37

ASP-like Tags

They can be recognized by their delimiters.  They start with <% and end with %>.  Additional character may appear after the initial <%, such as !, =, or @, to further specify the meaning of the tag.  Example: <%! double radius = 7.5; %> <%= 2 * Math.PI * radius %> <% if (radius > 10.0) { out.println("Exceeds recommended maximum"); } %> <%@ include file="copyright.html" %> 38 

ASP-like Tags… 

NOTE : All ASP-scripting like tags are self-contained.  All the information relevant to the tag, and all of the data it will act on, is contained within the individual tags themselves.  None of these scripting-oriented JSP tags have bodies. 39 

  



XML-like tags

They start with < and not <% Tag names have an embedded colon. They are similar to HTML tags; They can have a "start tag", a "tag body" and an "end tag". XML syntax is similar to HTML, but adds a few rules to avoid certain problems.  XML tags are case sensitive ( and <TITLE> are treated as two different tags).  All attribute values must be quoted (In HTML, quotes are optional).  All XML tags must also have a delimiting tag. 40<br /> <br /> Example 1. <jsp:forward page="admin.jsp"/> 2. <jsp:useBean id="login“<br /> <br /> class="UserBean"> <jsp:setProperty name="login“ property="group“ value="admin"/> </jsp:useBean> 41<br /> <br /> Components of a JSP program • HTML code • Comments • JSP tags • JSP Implicit Objects • Java Beans 42<br /> <br /> Comments in JSP<br /> <br /> 1. Plain HTML Comments Ex: <!-- hello --> Response: <!-- hello --><br /> <br /> 2. HTML Comments containing JSP tags Ex: < !-- value of 10 + 20 is <%= 10 + 20 %> --> Response: <!-- value of 10 + 20 is 30 --> 3. JSP Comment tag Ex: <%-- This is a JSP comment --%> Response: 4. Java Comments Ex: <%<br /> <br /> %><br /> <br /> /* int x; float f; */ void meth1() { //out.println( “hello output” ); } 43<br /> <br /> JSP tag types<br /> <br /> •Declaration tags •For variable and method declaration •Format: <%! Variable declaration; Method declaration; %> •Expression tags •For inserting Java expressions •format: <%= expression %> •Scriptlets •To embed java code blocks •format: <% code block %><br /> <br /> 44<br /> <br /> JSP tag types… •Directives<br /> <br /> • To specify information that affect the whole JSP program • format: <%@ directive_type directive_attribute %> •Action tags •Used to work with standard objects •format: <jsp:action_name action_attributes /> or <jsp:action_name action_attributes> … </jsp:action_name> 45<br /> <br /> <br /> <br /> General rules JSP tags are case sensitive<br /> <br /> <br /> <br /> Tags may have attributes<br /> <br /> <br /> <br /> Attribute values must always appear quoted<br /> <br /> <br /> <br /> White space with in the JSP page is not significant<br /> <br /> <br /> <br /> The \ character can be used as an escape sequence<br /> <br /> 46<br /> <br /> Sample Program -1<br /> <br /> •Using simple expression tag <html> <head> <title> My first JSP program<br /> <br /> The Current system date is :

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

47

Deploying JSP’s on TOMCAT

48

Deploying JSP’s on J2EE RI Server

49

Deploying JSP’s on Weblogic

50

Deploying JSP’s on JRun

51

Sample Program - 2

•Hello word example <%

String name = null; name = request.getParameter(“name”); if ( name == null ) { %> Hello, World <% } else { out.println(“Hello ” + name); } %>

52

Sample Program - 3

Java Version : <%= System.getProperty( "java.version" ) %>
Java Home : <%= System.getProperty( "java.home" ) %>
Os Name : <%= System.getProperty( "os.name" ) %>
User Name : <%= System.getProperty( "user.name" ) %>
User Home : <%= System.getProperty( "user.home" ) %>
User Directory : <%= System.getProperty( "user.dir" ) %>
53

Sample Program 4 •Simple usage of page directive, scriptlet and expression tags. <%@ page import="java.util.*" %> <% System.out.println( "Evaluating date now" ); Date date = new Date(); %> Hello! The time is now <%= date %> 54

Sample Program - 5

•Using page directive, declaration tag and expression tags together. <%@ page import="java.util.*" %> <%! Date dateobj = new Date(); Date getDate() { System.out.println( "In getDate() method" ); return dateobj; } %> Hello! The time is now <%= getDate() %>

55











Note about declaration tags Declarations in Declaration tag will become instance members. Variables in Declaration tags will be evaluated only once, during translation of the JSP page. Its behavior is same as definition of instance variables in a class. Hence it will not have different functionality for different clients. Client specific data must not be put in declaration tags, since they are shared. Sessions can be used for the purpose. 56

Control statements in JSP Sample Program - 6 •Using if condition statements <%! boolean validate_data( String value ) { if( value.trim().equals( "xyz" ) ) return true; else return false; } %> <% if( validate_data( "hello" ) ) { %>

Welcome, the data is valid

<% }else{ out.println( "

invalid data, try again

" ); } %> 57

Control statements in JSP

Sample Program 7 •Using for loops

<%! String items[] = { "bread", "rice", "dal" }; int quantity[] = { 2, 5, 3 }; double cost[] = { 12.50, 19.50, 28.75 }; %> <% for( int i =0; i < items.length; i++ ) { %> <% } %>
ITEM QUANTITY PRICE
<%= items[ i ] %> <%= quantity[ i ] %> <%= quantity[ i ] * cost[ i ] %>
58

Control statements in JSP

Sample Program - 8

•Another example of using for loops

<% String color_arr[] = { "00", "11", "22", "33", "44", "55", "66", "77", "88", "99", "AA", "BB", "CC", "DD", "EE", "FF" }; for(int i = 0; i < 5; i++ ) { String col = color_arr[ i * 3 ] + color_arr[ i * 3 ] + color_arr[ i * 3]; %> > > Welcome to Step India > <% }




%>

59

Built-in/Implicit JSP Objects •Besides objects explicitly created by a developer within JSP scripting elements, the JSP container provides a few internal objects, referred to as implicit objects. •The developer may assume that these objects will be automatically assigned to specific variable names. •They work as a shorthand for certain class/interface instances of Servlet/JSP API. •These Objects are available for ready usage. 60

JSP Objects description JSP object Servlet API Object

Description

application

javax.servlet.ServletContext Context (Execution environment) of the Servlet.

config

javax.servlet.ServletConfig

The ServletConfig for the JSP.

exception

java.lang.Throwable

The exception that resulted when an error occurred.

out

javax.servlet.jsp.JspWriter

An object that writes into a JSP's output stream. 61

JSP Objects description… JSP object Servlet API Object pageContext javax.servlet.jsp.PageContext

Description Page context for the JSP.

request

javax.servlet.HttpServletRequest The client request.

response

javax.servlet.HttpServletResponse

The response to the client.

session

javax.servlet.http.HttpSession

Session object created for requesting client.

page

javax.servlet.Servlet

Refers to current servlet object. 62

request object

•It provides access to data sent within a HTTP Request. Cookie[] Enumeration String String HttpSession HttpSession

getCookies() getHeaderNames() getQueryString() getRemoteUser() getSession() getSession(boolean create)

String boolean

getRequestedSessionId() isRequestedSessionIdValid()

Enumeration int String boolean boolean StringBuffer String String String

getHeaderNames() getIntHeader(java.lang.String name) getHeader(String name) isRequestedSessionIdFromCookie() isRequestedSessionIdFromURL() getRequestURL() getServletPath() getMethod() getContextPath()

63

Sample Program - 9 <%@ page language="java" contentType="text/html" %> The following information was received :
  • Request Method : <%= request.getMethod() %>
  • Request URI : <%= request.getRequestURI() %>
  • Request Protocol : <%= request.getProtocol() %>
  • Request Servlet Path : <%= request.getServletPath() %>
  • Request Query String : <%= request.getQueryString() %>
  • Request Sever Name : <%= request.getServerName() %>
  • Request Port : <%= request.getServerPort() %>
  • Request Address : <%= request.getRemoteAddr() %>
  • Request Browser : <%= request.getHeader("User-Agent") %>
64

response object

•It allows setting of response message including html Code, cookies, headers and other information. void void void void void boolean void String String void void

addCookie(Cookie cookie) addHeader( String name, String value) addIntHeader( String name, int value) setHeader( String name, String value) setIntHeader( String name, int value) containsHeader( String name) sendRedirect( String location) encodeRedirectURL(String url) encodeURL(String url) setStatus(int sc) setStatus(int sc, String sm) 65

Sample Program - 10

<% Cookie cookies[] = request.getCookies(); boolean flag = false; String name; try{ for( int i = 0; i < cookies.length; i++ ) { name = cookies[ i ] .getName(); out.println( name + " : " + cookies[ i ].getValue( ) + "
" ); if( name.trim().equals( "user_id" ) ) flag = true; } }catch( Exception e ){ System.out.println( e ); } if( ! flag ) { out.println( "No cookies found" ); response.addCookie( new Cookie( "user_id", "STEP" ) ); } %> 66

session object •It stores information for a particular user session. •Data stored in a session object are not discarded when the user jumps between pages in the application; they persist for the entire user session. •The web server destroys the session object when the session is invalidated. Object void Enumeration void void Object String[] void

getAttribute( String name) setAttribute( String name, Object value) getAttributeNames() removeAttribute( String name) putValue( String name, Object value) getValue( String name) getValueNames() removeValue( String name) 67

session object (Contd) String long long int void interval) ServletContext HttpSessionContext void boolean

getId() getCreationTime() getLastAccessedTime() getMaxInactiveInterval() setMaxInactiveInterval(int getServletContext() getSessionContext() invalidate() isNew() 68

Sample Program - 11

<%

java.util.Enumeration attribute_names = session.getAttributeNames(); String attr_name, attr_value; boolean entires_found_flag = false; if( attribute_names != null ) { while( attribute_names.hasMoreElements() ) { entires_found_flag = true; attr_name = (String) attribute_names.nextElement(); attr_value = (String) session.getAttribute( attr_name.trim() ); out.println( "value of the attribute " + attr_name + " is " + attr_value + "
" ); } } if( entires_found_flag == false ) { session.setAttribute( "attribute1", "value1" ); session.setAttribute( "attribute2", "value2" ); } %> 69

Sample Program - 12

What's your name?

A.jsp

<% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %> Continue

Hello, <%= session.getAttribute( "theName" ) %>

B.jsp

C.jsp 70

application object

•Allows interaction with Servlet container/environment. Object getAttribute(String name) Enumeration getAttributeNames() void removeAttribute( String name) void setAttribute(java.lang.String name, Object object) String getInitParameter(String name) Enumeration getInitParameterNames() String getServerInfo() int getMajorVersion() int getMinorVersion() String getMimeType( String file ) java.lang.String getRealPath(java.lang.String path) Servlet getServlet(java.lang.String name) Enumeration getServletNames() Enumeration getServlets() void log( Exception exception, String msg) void log( String msg) void log( String message, Throwable throwable) String getServletContextName() RequestDispatcher getRequestDispatcher(java.lang.String path) 71

Sample Program - 12

Display the default application settings

<% out.println( application.getServerInfo() + "

" ); java.util.Enumeration enum = application.getAttributeNames(); String element_name; while( enum.hasMoreElements() ) { element_name = (String) enum.nextElement(); out.println( "" + element_name + " ----------------" + application.getAttribute( element_name ) + "
"); } %> 72

config object

It passes configuration information to a servlet when it is instantiated. The information includes initialization parameters and the ServletContext object, which describes the context within which the servlet is running.

String Enumeration String ServletContext

getInitParameter(String name) getInitParameterNames() getServletName() getServletConext()

73

Sample Program - 13 <% java.util.Enumeration params = config.getInitParameterNames(); String name; out.println( "
    " ); while( params.hasMoreElements() ) { name = (String) params.nextElement(); out.println( "
  • " + name + "..." + config.getInitParameter( name.trim() )+ "
  • " ); } out.println( "
" ); %>

74

exception object

•It represents all errors and exceptions. It can be accessed in a JSP page that is declared as an error page using the isErrorPage attribute of the page directive. String getMessage() String printStackTrace() String toString()

75

out object

It defines an object for writing to JSP's output stream. void void int int boolean void

clearBuffer() flush() getBufferSize() getRemaining() isAutoFlush() newLine()

void void

print(...) println(...)

76

pagecontext object

•It stores information local to a JSP. •Each JSP has its own pageContext object that the server creates when the user accesses the page •It is deallocated when the user leaves the page. Object void void JspWriter Object ServletRequest ServletResponse ServletConfig ServletContext HttpSession Exception void void

findAttribute(String name) removeAttribute(String name) setAttribute(String name, Object attribute) getOut() getPage() getRequest() getResponse() getServletConfig() getServletContext() getSession() getException() forward(String path )  include( String path)     

77

Sample Code <% Object val = pageContext.findAttribute( pageContext.PAGE ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.APPLICATION ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.CONFIG ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.EXCEPTION ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.OUT ); out.println( val + "
" ); val = pageContext.findAttribute( pageContext.PAGECONTEXT ); out.println( val + "
" ); %> 78

JSP Standard Action Tags (XML format)

•They replace large sections of Java code. •Standard actions are actions that must be implemented by every JSP container. •They perform actions such as instantiating an object or changing an objects state. •JSP actions are a technique to separate business logic from presentation logic (removes Java code from JSP). •In reality, actions does not remove Java code but hides Java code from JSP author.79

JSP Action tags (Contd) 

Standard action tags start with the namespace prefix jsp followed by a colon and then by tag name.



Ex: <jsp:param>



Actions may have attributes and tag bodies.

80

Handling of Actions

JSP translators treat action tags as tokens that must be replaced with Java code.



Code for actions are defined in a tag library.



The translator simply replaces action tags with output of the code that is referenced by the action.



81

Handling of Actions…



Ex: The tag

<jsp:useBean id=“test” class=“one.two.Tester”>

will be replaced with Object test = (one.two.Tester) java.beans.Beans.instantiate( this.getClass().getClassLoader(), “one.two.Tester” );

82

  

Action tags Following action tags are available: <jsp:useBean> <jsp:getProperty>



<jsp:setProperty>



<jsp:param> <jsp:forward>

  

<jsp:include> <jsp:plugin> 83

useBean action tag

•It is used to access a Java bean (not EJB) in a JSP document. •Causes container to find an existing instance of the bean in the scope, with the specified id. If object is not found in that scope, container tries to create a new instance. •The setProperty and getProperty action tags are related to this tag. Syntax: <jsp:useBean attribute_name=attribute_value /> 84

Attributes in useBean tag Attribute

Function

id

Name used to refer the bean within the page. Must be unique.

scope

page/request/session/application.

class

Fully qualified bean class name.

beanName Bean name as per bean spec. type

Reference type (super class or same type). 85



Attributes in useBean tag Possible combination of attributes in

Possible combination of attributes in useBean tag:  





class  Creates an instance of given class class, type  Creates an instance of given class; the bean will have the given type. beanName, type  Creates an instance of given bean, bean will have the given type. type  if an object of the given type exists in the session, the id will refer that object. 86

setProperty action tag •It allows to set/assign a value for a bean property. •Bean id must be created using useBean tag before using setProperty and getProperty tags. •Syntax: <jsp:setProperty attr_name=attri_val /> Attributes: name property param value 87

Attributes in setProperty tag Attribute Description name Bean id specified in useBean. property Name of the property to be set. If individual bean property is specified, respective setter method will be invoked. If *, client request parameter with same name as bean property will be used to set the values. param Client request parameter whose value will be used to set the value. value Value to be assigned to the property. 88

Attributes in setProperty tag 

The name and property attributes are mandatory.



param and value attributes are mutually exclusive.



If param and value are not used, the tag attempts to use value of the request parameter with same name. 89

getProperty action tag •It allows to retrieve the value of a bean property. •Syntax: <jsp:getProperty attr_name=attri_val /> Attributes: name->bean id specified in useBean. property-> property whose value is to retrieved. 90

package test;

Bean access code 1 (bean)

public class StudentBean { private int id; private String name; public StudentBean() { id = -1; name = "---"; } public int getId() public void setId( int student_id ) public String getName() public void setName( String n )

test/StudentBean.java

{ { { {

return id; id = student_id; } return name; } name = n;

} }

} 91

Bean access code 1 (JSP) <jsp:useBean id="stBean" class="test.StudentBean" scope="page" /> Details Before changing the bean
Student id : <jsp:getProperty name="stBean" property="id" />
Student name : <jsp:getProperty name="stBean" property="name" />


<jsp:setProperty name="stBean" property="id" value="101" /> <jsp:setProperty name="stBean" property="name" value="step_student" /> Details After changing the bean
Student id : <jsp:getProperty name="stBean" property="id" />
Student name : <jsp:getProperty name="stBean" property="name" /> 92

Beans and Form processing package test2; public class UserData { String username; String email; int age;

UserData.java

public void setUsername( String value ){ public void setEmail( String value ){ public void setAge( int value ){

username = value; email = value;

age = value;

}

}

}

public String getUsername() { return username; } public String getEmail() { return email; } }

public int getAge() { return age; } 93

Beans and Form processing

What's your name?
What's your e-mail address?
What's your age? test.html

<jsp:useBean id="user" class="test2.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/>

Continue

<jsp:useBean id="user" class="test2.UserData" scope="session"/> The following data were received by the client
Name: <%= user.getUsername() %>
Email: <%= user.getEmail() %>
Age: <%= user.getAge() %>


beantest.jsp

result.jsp

94

Another Example package test3; public class User { private String id; private String surname;

}

public void setId( String id ){ this.id = id;} public String getId(){ return id; } public void setSurname( String surname ) { this.surname = surname; } public String getSurname( ){ return surname; } 95

Another Example <jsp:useBean id="userA" class="test3.User" /> <jsp:setProperty name="userA" property="surname" value="Smith" /> <jsp:setProperty name="userA" property="id" value="<%= 32 + 45 + "45" %>" /> Your data are as follows :
ID : <jsp:getProperty name="userA" property="id" />
SURNAME : <jsp:getProperty name="userA" property="surname" />

96

include action tag • It allows embedding of another page within the current jsp. • Included components must be valid JSP pages or servlets. • Note: Included file is not allowed to modify response headers, nor to set cookies in the response. • Syntax: <jsp:include page->file (Mandatory) flush->true/false (Optional)

97

How include action works

1.

2.

3.

Original JSP file stops processing and passes the request to included file. The included file generates its response. Response of the included file is returned to the calling JSP, which proceeds with its processing and generates the final response. 98

Sample Code <TITLE>Example Of The include Action Include the First File <jsp:include page="test1.jsp" />
Include the Second File: <jsp:include page="test2.jsp" />

99

forward action tag • It is used to transfer the control to another JSP, HTML or servlet. • It permanently transfers processing from one JSP to another on the local server. • Any content generated by the original page is discarded and processing begins anew at the second JSP. • Syntax: <jsp:forward page->url />

100







How forward action works Original JSP file stops processing and passes the request to forwarded component. Forwarded component generates the final response. Note:  

Execution never returns to the calling page. Only one effective forward action is valid in a JSP document, later forward actions are ignored. 101

Sample Code <TITLE>Example Of The forward Action <% if (Math.random() > .5) { %> <jsp:forward page=“one.jsp" /> <% } else { %> <jsp:forward page="two.jsp" /> <% } %> <%= System.getProperties() %> 102

param action tag

• It is used in conjunction (as a sub-tag) with include or forward action. • It is used to pass parameters to the resource being included/forwarded. • In the included/forwarded resource these parameters can be accessed using getParameter() method. • Syntax: <jsp:include …..> <jsp:param name->name value->value > . .

103

plugin action tag • It is used to embed objects for execution on client • It is similar to tag • Syntax: <jsp:plugin type->applet/bean code->class name codebase->codebase width->width height->height align->alignment archive->archive list nspluginurl->url iepluginurl->url />

104

Directives Directives give instructions to the JSP container to be interpreted at translation time. The general Syntax: <%@ directivename attribute=“value” attribute=”value”%> 



There are 3 directives  The page directive  The include directive  The taglib directive

105

Page Directive

Defines attributes applicable to the entire JSP page.  <%@ page atribute_name=attribute_value %>  Possible attributes  language=“java”  extends=“package.class”  import=“package.*, package.class,…”  session=“true”  buffer=“8kb”  autoFlush=“true”  isThreadSafe=“true”  info=“text”  errorPage=“relativeURL”  isErrorPage=“false”  contentType=“mimeType”  pageEncoding=encoding Note: The extends attribute is recommended not to be used. 106

Page Directive - Details

Attribute info language

Value

Text string Scripting lang

contentType MIME type,

Default

None “java” “text’html”

Example

info=“Registration form” language=“java” contentType=“text/java”

extends

Class name

None

extends=“com.gui.MyGUI”

import

Packages(s)

None

import=“java.net.URL” multiple imports separated by “,”

session

Boolean flag

“true”

session=“true”

buffer

Size or none

autoFlush

Boolean flag

“true”

autoFlush=“false”

isThreadSafeBoolean flag

“true”

isTheadSafe=“true”

errorPage

None

errorPage=“msg/failed.jsp”

“false”

isErrorPage=“false”

Local URL

isErrorPage Boolean flag

Server specific buffer=“12kb” buffer=“false”

107

Sample code



<%@page info="jaa re bakra" %> <%= getServletInfo() %> <%@page info="haal chaal kya khabar" %> --> <%= getServletInfo() %> 108

Handling Exceptions using errorPage



well come to error test <%@page errorPage="error.jsp" %> <%

int x = 10, y = 0; out.println( x/y ); out.println( "all is well" );

error_test.jsp

%> Hai how r u
<%@page isErrorPage="true" %>
<% out.println ( "error " + exception ); %>

Hello am fine

error.jsp

109

include Directive • Used to include a specified file's content into this page at translation time. • If the included file content changes, it is not reflected until server is restarted or until the main JSP file changes. • Only static pages are recommended to be included. • Syntax: <%@ include file=“file_name" %> 110

Sample Code



Hi, How r u <%@ include file="one.jsp" %> Hi, am doing fine

two.jsp

<%= "Hello World" %>



one.jsp <%= "Hello World" %>



111

include directive vs include action directive

action

Included at JSP Included at JSP translation time. request time. Inclusion is static in Inclusion is nature. dynamic. Recommended for Web component static/template usage recommended. data. Cannot pass Can pass parameters 112 parameters. using <param>

Tag libraries directive 113

Tag Libraries





JSP Tags can be of two types: 

Predefined tags: They have jsp: as prefix. Ex: jsp:include.



Custom tags: They are external, user defined tag library.

The ability to define custom tags were made possible in JSP 1.1 114

Tag Library



It is a collection of custom actions/tags, (portable elements) included in a JSP page.



Defining custom tags involve: 

Development of tag handlers for the tag.



Declaration of tag in tag library descriptor.



A tag library defines a set of related, custom tags and links them to objects (tag handlers) that implements functionality for the tags.



JSP container uses TLD to interpret/handle taglib directives inside JSP documents. 115

Advantages of Tag Library • Custom tags allow a convenient way to provide extension of JSP functionality. • Role segregation: • Tag libraries are created by Java developers which will be used by Web application designers. Hence division of labor between library developers and library users. • Enhanced productivity by hiding implementation details and encapsulating redundant code. 116

taglib Directive •It allows us to access user-defined/custom tags in a JSP. •Syntax: <%@ taglib uri=“tld uri” prefix=“unique name” %> •Both attributes are mandatory. •More than one taglib directive can be used in the same JSP. 117

Attribute uri

TLD files are stored in WEB-INF directory of WAR or in a subdirectory of WEB-INF.  You can reference a TLD directly or indirectly. Ex:  Direct reference  <%@ taglib uri="/WEB-INF/one.tld" prefix="tt" %>  Indirect reference (uses a short logical name)  <%@ taglib uri="/aab" prefix="tt" %>  Logical name is mapped to absolute location in deployment descriptor using following entries: /aab /web-inf/one.tld 118 

Custom tags and TLD •Custom tags are accessed in the JSP document using prefix name followed by the tag name. •Prefix names uniquely identify tags in spite of tag namespace reuse in different tag libraries. •A prefix can not be java, javax, jsp, jspx, servlet, sun and sunw. 119



Custom tags and TLD action Container takes necessary when custom tag is encountered.



When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on the respective tag handler.



The web container then invokes those operations when the JSP page’s servlet is executed. 120

TLD format

version (M) <jsp-version> compatible jsp version (O) <short-name> document name (M) Unique string (O) name in visual tools (O) <small-icon>small icon in visual tools (O) large icon in visual tools (O) <description> Description (O) ------------ ------------ 121



TLD format

unique tag name (M) tag handler class (M) TagExtraInfo class (O) Can be one of the following: empty/JSP/tagdependent (O) name in visual tools (O) <small-icon>small icon in visual tools (O) large icon in visual tools (O) <description> Description (O) scripting variable (O) (O) attribute name (M) <required> boolean value (O) (default -> false) boolean value (O) (default-> false) fully qualified data type of the attribute (O) ..... ………. .....
122

TLD Tag Description General Description elements/tags Tag

Description



Version number of library. (Must)

<jspversion>

Compliant JSP version.

<shortname>

Simple default name. Preferred prefix value in taglib directive. (Must)



Unique uri of the TLD document.

<description> Description/comments about TLD.

Contains elements describing the tag. 123

TLD Tag Description

Tags within the tag. Tag

Description Name of the tag Full class name of tag handler. Subclass of TagExtraInfo. Specifies whether tag can have content. Can be one of the following: tagdependent :- contains non-jsp code. JSP :- body contains JSP code. empty :- no body for this tag. Scripting variable information. Defines attributes for the tag. 124

TLD Tag Description Tags within the tag. Tag <required>





Description Defines attribute name. Specifies whether attribute is optional or not. (default – false) Values - true/false/yes/no Specifies whether the attribute value can be run time expression or static. Values - true/false/yes/no Specifies fully qualified data type. (Static values are always of type String). 125

TLD Tag Description Tags within the tag. Tag

Description



The variable name as a constant. Attribute name whose translation-time value will give name of the variable. One among name-given or name-from-attribute is mandatory. Fully qualified class name (type) of the variable. java.lang.String is default. <declare> Whether the variable refers to a new object. True is default. <scope> Scope of variable. NESTED is default. 126 126

TLD Tag Description Possible values for <scope> tag within tag Value

Availability

Methods

NESTED

Between start tag and end tag

In doInitBody and doAfterBody if tag handler implements BodyTag; otherwise, in doStartTag.

AT_BEGIN From start tag until end of the page

AT_END

After end tag until end of the page

doInitBody, doAfterBody & doEndTag id tag handler implements BodyTag; otherwise, in doStartTag & doEndTag. In doEndTag. 127

Code – tld file

1.0 <jsp-version>1.1 <short-name>dt <description>Gets the current System date today test.DateClass

128

Code – Java class

package test;

import java.util.Date; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class DateClass extends TagSupport { public int doEndTag() throws JspException { try{ Date dt = new Date(); String dt_str = "" + dt; pageContext.getOut().write( dt_str ); }catch( Exception e) return EVAL_PAGE;

{

System.out.println( e );

}

} }

129

Code – Jsp file <%@ page language="java" %> <%@ taglib uri="CurrentDate.tld" prefix="date" %>

The date & time now is :



130

Custom Tag types 131



Simple Tags A simple tag contains no body and no attributes.



Ex: <prefix_name:tag_name />



It would have the following entry in the respective TLD:

empty 132



Tags With Attributes A custom tag can have attributes listed in start tag having syntax attr="value".



Attributes customize behavior of a custom tag just as parameters customize the behavior of a method.



Attribute value can be a String constant or a runtime expression. Ex:

4. 5.

<prefix_name:tag_name attr=“val" /> <prefix_name:tag_name attr1="<%=bookDB.getBooks()%>" attrib2="val" />

133



Tags with Bodies A custom tag can contain custom and core

tags, scripting elements, HTML text, and tag-dependent body content between the start and end tag.  Ex: <prefix_name:tag_name attrib_name="val" /> <% cart.clear(); %> <strong> You just cleared your shopping cart!
 
134



Tags That Define Scripting Variables A custom tag can define a variable that can be used in scripts within a page.

1) <% tx.begin(); %> 2) <jsp:getProperty name="book" property="title"> 135



Cooperating Tags Custom tags can cooperate with each

other through shared objects. In the following example, tag1 creates an object called obj1, which is then reused by tag2. Also an object created by enclosing tag is available to all inner tags. 136 









Tag Handlers It is a Java class that implements behavior of a custom tag. It is invoked by Web container to evaluate a custom tag during execution of JSP page that references the tag. They must implement either Tag or BodyTag interface, preferably via TagSupport and BodyTagSupport classes respectively. Tag handlers will be referenced in TLD files. 137

Tag Handlers…



When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on tag handler. The container then invokes those operations when the JSP page's Servlet is executed.



Note: A tag handler has access to an API that allows it to communicate with the JSP page. Entry point to the API is PageContext, through which a tag handler can retrieve all implicit objects accessible from a JSP page. 138

Package javax.servlet.jsp.tagex t 139

Interface Hierarchy

140

Tag

It defines a handler for simple tags which does not manipulate tag body.



It specifies a framework (protocol) for interaction between a Tag handler and JSP page implementation class.



i.e. it defines the life cycle methods to be invoked at start and end tag.



It specifies accessor methods for pageContext and parent properties.



141

void void int int Tag void 

Tag – Method summary pc) setPageContext(PageContext setParent(Tag t) doStartTag() doEndTag() getParent() release()

JSP page implementation object invokes setPageContext and setParent, in that order, before invoking doStartTag() or doEndTag().

142

Tag - Field Summary 







static int SKIP_BODY Skip body evaluation. static int EVAL_BODY_INCLUDE Evaluate the tag body. static int SKIP_PAGE Skip the rest of the page. static int EVAL_PAGE Continue evaluating the page. 143

Tag - Field usage •If the TLD file indicates that the action tag must be empty, then doStartTag() must return SKIP_BODY. •Otherwise, the doStartTag() method may return SKIP_BODY or EVAL_BODY_INCLUDE. •If SKIP_BODY is returned and if body is present, body is not evaluated. •If EVAL_BODY_INCLUDE is returned, the body is evaluated and "passed through" to the current out. 144

Sample code A simple tag for example would

be implemented by the following tag handler:

public SimpleTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello."); } catch (Exception ex) { pageContext.getOut().print("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } 145 }

IterationTag









It extends Tag by defining one additional method ( doAfterBody() ) that processes tag body. The doAfterBody() is invoked after every body evaluation if doStartTag() returns EVAL_BODY_INCLUDE. If it returns EVAL_BODY_AGAIN, then the body will be reevaluated. If it returns SKIP_BODY, then the body reevaluation will be skipped and doEndTag() is invoked. 146

IterationTag Members Field Summary  static int EVAL_BODY_AGAIN Request reevaluation of body content. Method Summary  int doAfterBody() Process body content. 147



BodyTag It extends IterationTag and defines additional methods that let a tag handler to manipulate body content by providing buffering.



While implementing BodyTag, the doStartTag() can return SKIP_BODY, EVAL_BODY_INCLUDE or EVAL_BODY_BUFFERED.

148

BodyTag… •If EVAL_BODY_BUFFERED is returned, then a BodyContent object will be created by the container to encapsulate the body. •The container creates BodyContent object by calling pushBody() of the current pageContext. •The container returns this object to JSP by calling popBody() of the PageContext. 149

Field Summary int EVAL_BODY_BUFFERED Request the creation of new buffer, a BodyContent on which to evaluate the body of this tag. int EVAL_BODY_TAG Deprecated as of Java JSP API 1.2, use BodyTag.EVAL_BODY_BUFFERED or IterationTag.EVAL_BODY_AGAIN. 150

Method Summary void setBodyContent(BodyContent b) Sets the bodyContent. It will be invoked by container.

void doInitBody() Action method to handle body evaluation. Invoked after setBodyContent().

Both methods will be invoked only if doStartTag() 151 returns EVAL_BODY_BUFFERED

BodyTag - Field usage •If TLD file indicates that action must be empty, then doStartTag() must return SKIP_BODY. •Otherwise, doStartTag() may return SKIP_BODY, EVAL_BODY_INCLUDE, or EVAL_BODY_BUFFERED. •If SKIP_BODY is returned, body is not evaluated and doEndTag() is invoked. 152

BodyTag - Field usage… •If EVAL_BODY_INCLUDE is returned, setBodyContent() and doInitBody() will not be invoked, the body is evaluated and "passed through" to the current out, doAfterBody() followed by doEndTag() is invoked. •If EVAL_BODY_BUFFERED is returned, setBodyContent() followed by doInitBody() is invoked, the body is evaluated, doAfterBody() followed by doEndTag() is invoked.

153

Interface TryCatchFinally •It provides as optional support for tag handlers implementing Tag, IterationTag or BodyTag. Method Summary void doCatch( Throwable t ) Will be invoked if a Throwable occurs while evaluating BODY. void doFinally() Will be invoked in all cases after doEndTag() for any class implementing Tag, IterationTag or BodyTag. 154

Class Hierarchy

155



Class TagSupport Is a utility class to be extended by new tag handlers instead of implementing Tag/IterationTag.



It implements Tag and IterationTag and adds additional methods including getter methods for the properties in Tag.



It is further extended by BodyTagSupport.



It has one static method that facilitates coordination among cooperating tags. 156

 

Field Summary protected String id protected PageContext

pageContext

Fields inherited from Tag  EVAL_BODY_INCLUDE  EVAL_PAGE  SKIP_BODY  SKIP_PAGE Fields inherited from IterationTag  EVAL_BODY_AGAIN

157

Method Summary

int doStartTag() Default processing of start tag.  int doEndTag() Default processing of end tag.  int doAfterBody() Default processing for a body. 

static Tag findAncestorWithClass(Tag from, Class klass) Find instance of given type closest to given tag. 

String getId() The value of the id attribute of this tag; or null.  void setId(String id) Set the id attribute for this tag. 

158

Method Summary…

Tag getParent() The Tag instance most closely enclosing this tag instance.  void setParent(Tag t) Set the nesting tag of this tag. 

Object getValue(String k) Get a the value associated with a key.  Enumeration getValues()  void setValue(String k, Object o)  void removeValue(String k) 



void setPageContext(PageContext pageContext)



void release()

159

Class BodyTagSupport



A base class for defining tag handlers implementing BodyTag.



It implements BodyTag, IterationTag, Serializable and Tag interfaces



It adds additional methods including getter methods for bodyContent property and methods to get the previous out (JspWriter).

160

Field Summary

protected BodyContent bodyContent Fields inherited from TagSupport  Id  pageContext Fields inherited from interface Tag  EVAL_BODY_INCLUDE  EVAL_PAGE  SKIP_BODY, SKIP_PAGE Fields inherited from interface IterationTag  EVAL_BODY_AGAIN Fields inherited from interface BodyTag  EVAL_BODY_BUFFERED  EVAL_BODY_TAG (Deprecated) 

161



Method Summary int doStartTag()

Default processing of start tag.  void setBodyContent(BodyContent b) Prepare for evaluation of the body; store bodyContent.  void doInitBody() Prepare for body evaluation just before first body evaluation.  int doAfterBody() After body evaluation.  int doEndTag() 162 Default processing of the end tag.



Method Summary…

BodyContent getBodyContent()

Get current bodyContent. 

JspWriter getPreviousOut()

Get the out (JspWriter). 

void release()

163

  

 



Class BodyContent It extends JspWriter. It encapsulates evaluated body content. Since it encapsulates the result of evaluation, it will not contain actions and the like, but the result of their invocation. Its buffer size is unbounded. A BodyContent is made available to a BodyTag through a setBodyContent() call. Tag handlers can use it until after the call to doEndTag(). 164



Method Summary protected BodyContent(JspWriter e)

void clearBody()  abstract java.io.Reader getReader() Return value of this BodyContent as a Reader.  abstract String getString() Return value of the BodyContent as a String.  abstract void writeOut(java.io.Writer out) Write contents of this BodyContent into a Writer. 

165







Class TagExtraInfo

Optional class specified in the TLD to describe additional translation-time information not described in the TLD. TagExtraInfo class must be mentioned in TLD file. This class can be used: 



to indicate that the tag defines scripting variables to perform translation-time validation of the tag attributes.

166



Method Summary TagInfo getTagInfo()

Get the TagInfo for this class.  VariableInfo[] getVariableInfo(TagData data) information on scripting variables defined by the tag associated with this TagExtraInfo instance.  boolean isValid(TagData data) Translation-time validation of the attributes.  void setTagInfo(TagInfo tagInfo) Set the TagInfo for this class. 167



Class TagInfo Tag information for a tag in a Tag

Library; This class is instantiated from the TLD and is available only at translation time.

168

Field Summary

static String BODY_CONTENT_EMPTY static constant for getBodyContent() when it is empty  static String BODY_CONTENT_JSP static constant for getBodyContent() when it is JSP  static String BODY_CONTENT_TAG_DEPENDENT static constant for getBodyContent() when it is Tag dependent 

169



Method Summary String getTagName()



String getTagClassName()



TagExtraInfo getTagExtraInfo()

The instance (if any) for extra tag information 

String getBodyContent()



String getDisplayName()



String getSmallIcon()



String getLargeIcon()



String getInfoString()

170



Method Summary… TagAttributeInfo[] getAttributes()



TagVariableInfo[] getTagVariableInfos()



TagLibraryInfo getTagLibrary()

boolean isValid(TagData data) Translation-time validation of attributes. 

171





Class VariableInfo Provides information about scripting

variables. This information is provided by TagExtraInfo classes and it is used during translation of JSP.

172

Member summary Field Summary   

static int AT_BEGIN static int AT_END static int NESTED

Method Summary  String getVarName()  String getClassName()  boolean getDeclare()  int getScope()

173

Class TagVariableInfo



Provides scripting variable information for a tag in a Tag Library.



This class is instantiated from the TLD and is available only at translation time.



This information is only available in JSP1.2

174

Method Summary



String getNameGiven()



String getNameFromAttribute()



String getClassName()



boolean getDeclare()



int getScope()

175

Class TagAttributeInfo



Provides information about attributes of a Tag, available at translation time.



This class is instantiated from TLD file.



Only the information needed to generate code is included here.

176

Method Summary    

String getName() boolean isRequired() boolean canBeRequestTime() String getTypeName()

177



Class TagLibraryInfo

Translation-time information associated with a taglib directive, and its underlying TLD file. Most of the information is directly from the TLD, except for the prefix and the uri values used in the taglib directive.

178



Field Summary protected String tlibversion



protected String jspversion



protected String shortname



protected String uri



protected String info



protected TagInfo[] tags 179

Method Summary



String getRequiredVersion()



String getShortName()



String getURI()



String getInfoString()



TagInfo getTag(java.lang.String shortname)



TagInfo[] getTags() 180

Class PageData •Provides information about the JSP page during translation time. •Information corresponds to XML view of JSP page contents. •It is instantiated and used by the container. Method Summary abstract InputStream getInputStream() Returns input stream on the XML view (include directives will be expanded) of a JSP page. 181

Class TagAttributeInfo •Provides information about Tag attributes, available at translation time. •It is instantiated using information in the TLD file. Field Summary static String ID

"id" is wired in to be ID.

Constructor Summary TagAttributeInfo( String name, boolean required, String type, boolean reqTime)

182

Method Summary boolean canBeRequestTime() Determines whether this attribute can hold a request-time value. static TagAttributeInfo getIdAttribute(TagAttributeInfo[] a) Convenience static method that goes through an array of TagAttributeInfo objects and looks for "id". String getName() The name of this attribute. String getTypeName() The type (as a String) of this attribute. boolean isRequired() Whether this attribute is required.

183

Class TagData Provides information about attribute/value for a tag instance at translation-time only. •It is only used as an argument to isValid() and getVariableInfo() of TagExtraInfo, which are invoked at translation time.

Object getAttribute(String attName) Enumeration getAttributes() String getAttributeString(String attName) void setAttribute( String attName, Object value) 184

Writing Tag Handlers

185











Simple tags Handler for simple tag must implement

doStartTag and doEndTag methods of Tag interface. Method doStartTag is invoked when the start tag is encountered. Method doStartTag must return SKIP_BODY since simple tags have no body. Method doEndTag is invoked when the end tag is encountered. Method doEndTag needs to return EVAL_PAGE if the rest of the page needs to be evaluated; otherwise, it should return SKIP_PAGE. 186

Simple tag - Example

A simple tag would be implemented by the following tag handler: public SimpleTag extends TagSupport { public int doStartTag() throws JspException { try { pageContext.getOut().print("Hello."); } catch (Exception ex) { throw new JspTagException("SimpleTag: " + ex.getMessage()); } return SKIP_BODY; } public int doEndTag() { return EVAL_PAGE; } }

187



Tags with Attributes In this case for each attribute, the Tag

Handler must define a property as well as get and set methods that conform to JavaBeans architecture conventions.  Ex: Tag handler for following tag in JSP, <prefix:tag_name parameter="Clear"> contains the following declaration and methods: private String parameter = null; public String getParameter() { return parameter; } public void setParameter(String parameter) { this.parameter = parameter; } 188



Attribute Validation The tag library documentation should describe valid values for tag attributes.



During JSP translation, container enforces constraints contained in TLD for each attribute.



Attributes passed to a tag can also be validated during translation using isValid method of a class derived from TagExtraInfo.



Method isValid is passed a TagData object, which contains information about each attribute. 189



Attribute Validation using TagExtraInfo

The tag has the following TLD attribute element:

attr1 <required>true true

This declaration indicates that the value of attr1 can be determined at runtime.



The following isValid method checks that the value of attr1 is a valid Boolean value. 190

Attribute Validation… public class TEI extends TagExtraInfo {

}

public boolean isValid(Tagdata data) { Object o = data.getAttribute("attr1"); if (o != null ) { if ( ((String)o).toLowerCase().equals("true") ) return true; else return false; } else return false; } 191



Tags with Bodies A tag handler for a tag with body is implemented differently depending on whether the tag handler needs to interact with the body or not.



A tag is said to interact with body content if the tag handler reads/modifies body content.

192



Tag Handler Does Not Interact with Body If tag handler does not need to interact with

body, it should implement Tag interface or extend TagSupport.  If tag body needs to be evaluated, doStartTag method must return EVAL_BODY_INCLUDE; otherwise it should return SKIP_BODY. If a tag handler needs to iteratively evaluate the body, it should implement IterationTag or extend TagSupport.  It should return EVAL_BODY_AGAIN from the doStartTag and doAfterBody methods if the body needs to be evaluated again. 193 



Tag Handler Interacts with Body If tag handler needs to interact with body, it must implement BodyTag or extend BodyTagSupport.



Such handlers implement doInitBody and doAfterBody.



These methods have access to BodyContent object, which provides several methods to read and write body.



A tag handler can use BodyContent's getString or getReader methods to extract body information and writeOut(out) to write the body contents to out stream.



The parameter supplied to writeOut method is obtained using tag handler's getPreviousOut method.



This method ensures that a tag handler's results are available to an enclosing tag handler.



If tag body needs to be evaluated, doStartTag needs to return EVAL_BODY_BUFFERED; otherwise, it should return SKIP_BODY. 194

Tag Handler Interacts with Body… doInitBody Method It is called before body content is evaluated and hence is generally used to perform any initialization that depends on body content. doAfterBody Method  It is called after the body content is evaluated.  Like doStartTag method, doAfterBody must return an indication of whether to continue evaluating body.  Thus, if body should be evaluated again, doAfterBody should return EVAL_BODY_BUFFERED; otherwise, it should return SKIP_BODY. release Method  A tag handler should release any private resources in the release method. 195 

Tag Handler Interacts with Body…

The tag handler below reads body content (which contains a SQL query) and executes the query. Since body does not need to be reevaluated, doAfterBody returns SKIP_BODY. public class QueryTag extends BodyTagSupport { public int doAfterBody() throws JspTagException { BodyContent bc = getBodyContent(); String query = bc.getString(); try { Statement stmt = connection.createStatement(); ResultSet result = stmt.executeQuery(query); …….. } catch (SQLException e) { throw new JspTagException("QueryTag: " + e); } return SKIP_BODY; } } 196 

Tag Handler Interacts with Body… body-content Element body-content Element



For tags that have a body, body content type must be specified using body-content element:

JSP/tagdependent

Body content containing custom/core tags, scripting elements, and HTML text is categorized as JSP.



All other types of body content--for example--SQL statements would be labeled tagdependent.

Note: Value of body-content element does not affect body interpretation by tag handler; It is only intended to be used by an authoring tool for body content. 197



Tags with scripting variables A tag handler is responsible for creating or setting object referred by scripting variable into a context accessible from the page.



This is done using method pageContext.setAttribute( name, value, scope)



Typically an attribute passed to custom tag specifies name of the scripting variable object; this name can be retrieved by invoking the attribute's get method described in Using Scope Objects. 198

Tags with scripting variables



Scripting variable value is retrieved using pageContext.getAttribute( name, scope).



The usual procedure is that the tag handler retrieves a scripting variable, performs some processing on the object, and then sets scripting variable's value using pageContext.setAttribute( name, object) 199



The table below summarizes object scopes. Name

Accessible From

Lifetime

page

Current page

Until response has been sent back to user or request is passed to a new page

request

Current and any included or forwarded pages

Until the response has been sent back to the user

session

Current request and any subsequent request from same browser (subject to session lifetime)

Life of user's session

Current and any future application request from the same Web application

Life of the application 200



Providing Information about Scripting Variable The example below defines a scripting

variable book that is used for accessing book information: <%=messages.getString("CartRemoved")%> <strong><jsp:getProperty name="book“ property="title"/>
 
201



  





When the JSP page containing this tag is translated, the Web container generates code to synchronize the scripting variable with the object referenced by the variable. To generate the code, the Web container requires certain information about the scripting variable: Variable name Variable class Whether the variable refers to a new or existing object The availability of the variable. There are two ways to provide this information: by specifying the variable TLD subelement or by defining a tag extra info class and including the tei-class element in the TLD. Using the variable element is 202 simpler, but slightly less flexible.

Thank You 203

Related Documents

Jsp
April 2020 36
Jsp
May 2020 27
Jsp
May 2020 14
Jsp
May 2020 14
Jsp
July 2020 16
Jsp
November 2019 49

More Documents from ""

Threads
May 2020 26
Jsp
May 2020 21
Servlet
May 2020 21
Ajax
May 2020 36
Wml
May 2020 18