Programming

1

Understanding •Java Server Pages is another technology JSP

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 They are HTML documents which are

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 •JSP’s being Java programs, they allow
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 developers and JSP being vendor-neutral,
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 restart when Does not require server
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 of Servlets first appeared as part
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 create RAD tools are now available to
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 vsAsp ASP Features
WEB Server Platform Reusable components Memory leak protection Scripting languages Security Customized tags IIS, PWS Com No Many Windows Any Yes

Jsp

Javabeans/EJB

J-script, Java VB-script No yes 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

 

Differences

JSP vs Servlets

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

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

Comparing servlet and JSP code

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("<HTML>"); 13. out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>"); 14. out.println("<BODY>"); 15. out.println("<BIG>Hello World</BIG>"); 16. out.println("</BODY></HTML>"); 17. } 18. }
14

Comparing servlet and JSP code
1. <HTML> 2. <HEAD> <TITLE>Hello World</TITLE></HEAD> 3. <BODY> 4. <h2>Hello World </h1> 5. </BODY> 6. </HTML>

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
st que Re

Translation by JSP engine Generated Servlet Compilation

Web Client
Re sp

on

se

Compiled Servlet Instantiation Servlet is loaded to server
16

JSP functionality architecture

17

  

jspInit() jspDestroy() _jspService( request, response )
jspInit()
Initialise JSP Invoked only once Handle Requests: invoked for every request

JSP life cycle
_jspService(request,response) jspDestroy()
Invoked by container to cleanup

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

JSPbetween the JSP Engine and the JSP engine and JSP Contract

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

•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()

Interface javax.servlet.Servlet

21

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

Interface interaction that a JSP JspPage It describes the generic
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

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 JspFactory

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

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.

Field Summary…

   

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

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

Method Summary

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

  

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

Class JspWriter

      

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 of JSP tags usage is similar to those
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

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

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

  

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 (<title> 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

XML-like tags

Example
1. <jsp:forward page="admin.jsp"/> 2. <jsp:useBean id="login“
class="UserBean"> <jsp:setProperty name="login“ property="group“ value="admin"/> </jsp:useBean>
41

Components of a JSP program
• HTML code • Comments • JSP tags • JSP Implicit Objects • Java Beans
42

1. Plain HTML Comments Ex: <!-- hello --> Response: <!-- hello -->

Comments in JSP

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: <% /* int x; float f; */ void meth1() { //out.println( “hello output” ); }
43

%>

•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 %>

JSP tag types

44

• 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

JSP tag types… •Directives

General rules JSP tags are case sensitive
Tags may have attributes Attribute values must always appear quoted White space with in the JSP page is not significant The \ character can be used as an escape sequence

46

•Using simple expression tag
<html> <head> <title> My first JSP program

Sample Program -1

</title> </head> <body> <b> The Current system date is : <h1> <%= new java.util.Date() %> </h1> </b> </body> </html>
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

•Hello word example <%

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

52

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

Sample Program - 3

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

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

Sample Program - 5

55

Note about declaration tags will become Declarations in Declaration tag
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
<html> <body> <%! boolean validate_data( String value ) { if( value.trim().equals( "xyz" ) ) return true; else return false; } %> <% if( validate_data( "hello" ) ) { %> <h1> Welcome, the data is valid </h1> <% }else{ out.println( "<h1> invalid data, try again </h1>" ); } %> </body> </html>
57

Sample Program - 7 •Using for loops

Control statements in JSP

<html> <body> <%! String items[] = { "bread", "rice", "dal" }; int quantity[] = { 2, 5, 3 }; double cost[] = { 12.50, 19.50, 28.75 }; %> <table align="center" bgcolor="yellow" border ="1" width="75%" > <tr> <td> ITEM </td> <td> QUANTITY </td> <td> PRICE </td> </tr> <% for( int i =0; i < items.length; i++ ) { %> <tr> <td> <%= items[ i ] %> </td> <td> <%= quantity[ i ] %> </td> <td> <%= quantity[ i ] * cost[ i ] %> </td> </tr> <% } %> </table> </body> </html>
58

Control statements in JSP
•Another example of using for loops

Sample Program - 8

<html> <body> <center> <% 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]; %> <h<%= i %> > <font color=<%=col%> > Welcome to Step India </h<%= i %> > <% } </center> </body> </html> %> </font>

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
application config exception out

Description

javax.servlet.ServletContext Context (Execution environment) of the Servlet. javax.servlet.ServletConfig java.lang.Throwable The ServletConfig for the JSP. The exception that resulted when an error occurred. An object that writes into a JSP's output stream.
61

javax.servlet.jsp.JspWriter

JSP Objects description…
JSP object Servlet API Object pageContext javax.servlet.jsp.PageContext request response session Description
Page context for the JSP. javax.servlet.HttpServletRequest The client request.
javax.servlet.HttpServletResponse

The response to the client. Session object created for requesting client. Refers to current servlet object.
62

javax.servlet.http.HttpSession

page

javax.servlet.Servlet

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

request object

getCookies() getHeaderNames() getQueryString() getRemoteUser() getSession() getSession(boolean create)
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" %> <html> <body bgcolor="white" > The following information was received : <ul> <li> Request Method : <%= request.getMethod() %> <li> Request URI : <%= request.getRequestURI() %> <li> Request Protocol : <%= request.getProtocol() %> <li> Request Servlet Path : <%= request.getServletPath() %> <li> Request Query String : <%= request.getQueryString() %> <li> Request Sever Name : <%= request.getServerName() %> <li> Request Port : <%= request.getServerPort() %> <li> Request Address : <%= request.getRemoteAddr() %> <li> Request Browser : <%= request.getHeader("User-Agent") %> </ul> </body> </html>
64

•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

response object

<html> <body> <% 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( ) + "<br>" ); 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" ) ); } %></body></hml>
66

Sample Program - 10

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

<html> <body> <%

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 + "<br>" ); } } if( entires_found_flag == false ) { session.setAttribute( "attribute1", "value1" ); session.setAttribute( "attribute2", "value2" ); } %> </body> </html>
69

<HTML> <BODY> <FORM METHOD=POST ACTION="http://localhost:8080/aaa/B.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20> <P><INPUT TYPE=SUBMIT> A.jsp </FORM> </BODY> </HTML> <% String name = request.getParameter( "username" ); session.setAttribute( "theName", name ); %> <HTML> <BODY> <A HREF="http://localhost:8080/aaa/C.jsp">Continue</A> </BODY></HTML>

Sample Program - 12

B.jsp

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

C.jsp
70

•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

application object

Sample Program - 12
<HTML> <BODY> <h2>Display the default application settings</h2> <% out.println( application.getServerInfo() + "<br><br>" ); java.util.Enumeration enum = application.getAttributeNames(); String element_name; while( enum.hasMoreElements() ) { element_name = (String) enum.nextElement(); out.println( "<b>" + element_name + "</b> ----------------" + application.getAttribute( element_name ) + "<br>"); } %> </BODY> </HTML>
72

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.

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

String Enumeration String ServletContext

73

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

74

•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()

exception object

75

It defines an object for writing to JSP's output stream.
void void int int boolean void void void clearBuffer() flush() getBufferSize() getRemaining() isAutoFlush() newLine() print(...) println(...)

out object

76

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

pagecontext object

77

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

JSP Standard Action Tags
•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

(XML format)

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

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

Handling of Actions…

<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

   

Actionare available: tags Following action tags
<jsp:useBean> <jsp:getProperty> <jsp:setProperty> <jsp:param> <jsp:forward> <jsp:include> <jsp:plugin>
83

   

•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

useBean action tag

Attributes in useBean tag
Attribute
id scope class type

Function
Name used to refer the bean within the page. Must be unique. page/request/session/application. Fully qualified bean class name. Reference type (super class or same type).
85

beanName Bean name as per bean spec.

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)
test/StudentBean.java

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

{ { { {

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

} }
91

Bean access code 1 (JSP)
<jsp:useBean id="stBean" class="test.StudentBean" scope="page" /> <html> <body> Details Before changing the bean <br> Student id : <jsp:getProperty name="stBean" property="id" /> <br> Student name : <jsp:getProperty name="stBean" property="name" /> <br> <br> <br> <jsp:setProperty name="stBean" property="id" value="101" /> <jsp:setProperty name="stBean" property="name" value="step_student" /> Details After changing the bean <br> Student id : <jsp:getProperty name="stBean" property="id" /> <br> Student name : <jsp:getProperty name="stBean" property="name" /> </body> </html>
92

Beans and Form processing
package test2; public class UserData { String username; String email; int age; public void setUsername( String value ){ public void setEmail( String value ){ public void setAge( int value ){

UserData.java

username = value; email = value; } }

}

age = value;

public String getUsername() { return username; } public String getEmail() { return email; } } public int getAge() { return age; }
93

<HTML> <BODY> <FORM METHOD=POST ACTION="beantest.jsp"> What's your name? <INPUT TYPE=TEXT NAME=username SIZE=20><BR> What's your e-mail address? <INPUT TYPE=TEXT NAME=email SIZE=20><BR> What's your age? <INPUT TYPE=TEXT NAME=age SIZE=4> test.html <P><INPUT TYPE=SUBMIT> </FORM></BODY> </HTML> <jsp:useBean id="user" class="test2.UserData" scope="session"/> <jsp:setProperty name="user" property="*"/> <HTML> <BODY> <A HREF=result.jsp>Continue</A>

Beans and Form processing

beantest.jsp
</BODY> </HTML>

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

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 : <br> ID : <jsp:getProperty name="userA" property="id" /> <br> 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

1.

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

How include action works

2.

3.

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

99

forward actionto another tag • It is used to transfer the control
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
<HTML> <HEAD><TITLE>Example Of The forward Action</TITLE></HEAD> <BODY> <% if (Math.random() > .5) { %> <jsp:forward page=“one.jsp" /> <% } else { %> <jsp:forward page="two.jsp" /> <% } %> <%= System.getProperties() %> </BODY> </HTML>
102

• 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 > . . </jsp:include>

param action tag

103

plugin objects for execution on action tag • It is used to embed
client • It is similar to <applet> 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

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

Attribute info language

Page Directive - Details
Value Default Example Text string Scripting lang None “java” “text’html” None None “true” “true” “true” None “false” info=“Registration form” language=“java” contentType=“text/java” extends=“com.gui.MyGUI” import=“java.net.URL” multiple imports separated by “,” session=“true” autoFlush=“false” isTheadSafe=“true” errorPage=“msg/failed.jsp” isErrorPage=“false”
107

contentType MIME type, extends import session buffer autoFlush errorPage Class name Packages(s) Boolean flag Size or none Boolean flag Local URL

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

isThreadSafeBoolean flag isErrorPage Boolean flag

<html> <body>

Sample code
<%@page info="jaa re bakra" %> <%= getServletInfo() %> </body>

</html> <html> <body> <!-<%= "hello" %> <%@page info="haal chaal kya khabar" %> --> <%= getServletInfo() %> </body> </html>
108

<html> <body>

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

</body> </html> <html> <body> Hai how r u <br/> <%@page isErrorPage="true" %> <br> <% out.println ( "error " + exception ); %> <br/> <br/> Hello am fine </body> </html>

error.jsp

109

include specified file's content Directive • Used to include a
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

<html> <body>

Sample Code
Hi, How r u <%@ include file="one.jsp" %> Hi, am doing fine </body> two.jsp

</html> <html> <body> <b> <%= "Hello World" %> </b> <h1> <%= "Hello World" %> </h1> </body> </html>
111

one.jsp

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 <taglib> directive
113

JSP Tags can be of two types:

Tag Libraries

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

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

Tag Library

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

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: <taglib> <taglib-uri>/aab</taglib-uri> <taglib-location>/web-inf/one.tld</taglib-location> </taglib> 118

Attribute uri

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 Container takes necessary action
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

<?xml version="1.0"> <!DOCTYPE taglib SYSTEM "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlib-version> version (M) </tlibversion> <jsp-version> compatible jsp version (O) </jspversion> <short-name> document name (M) </shortname> <uri> Unique string (O) </uri> <display-name>name in visual tools (O) </display-name> <small-icon>small icon in visual tools (O) </small-icon> <large-icon>large icon in visual tools (O) </large-icon> <description> Description (O) </description> <tag>------------ </tag> <tag>------------ </tag> 121 </taglib>

TLD format

<tag>

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

TLD format

TLD Tag Description General Description elements/tags
Tag
<tlibversion> <jspversion> <shortname> <uri> <tag>

Description
Version number of library. (Must) Compliant JSP version. Simple default name. Preferred prefix value in taglib directive. (Must) Unique uri of the TLD document. Contains elements describing the tag.
123

<description> Description/comments about TLD.

Tags within the <tag> tag.
Tag <name> <tag-class> <tei-class> <bodycontent>

TLD Tag Description

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. <variable> Scripting variable information. <attribute> Defines attributes for the tag. 124

TLD Tag Description Tags within the <attribute> tag.
Tag
<name> <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

<rtexprvalue>

<type>

TLD Tag Description Tags within the <variable> tag.
Tag
<name-given> <name-fromattribute>

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. <variable-class> 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 for <scope> tag within <variable> tag Tag Description Possible values
Value
NESTED

Availability
Between start tag and end tag

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

AT_BEGIN From start tag until
end of the page

AT_END

After end tag until end of the page

<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.1</jsp-version> <short-name>dt</short-name> <description>Gets the current System date</description> <tag> <name>today</name> <tag-class>test.DateClass</tag-class> </tag> </taglib>

Code – tld file

128

package test;

Code – Java class

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; } }
129

{

System.out.println( e );

}

Code – Jsp file
<%@ page language="java" %> <%@ taglib uri="CurrentDate.tld" prefix="date" %> <html> <body> <h1> The date & time now is : <date:today /> </h1> </body> </html>

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:

<body-content>empty</body-content>
132

Tags With Attributesin A custom tag can have attributes listed
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: <prefix_name:tag_name attr=“val" /> <prefix_name:tag_name attr1="<%=bookDB.getBooks()%>" attrib2="val" />

4. 5.

133

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(); %> <font color="#ff0000" size="+2"><strong> You just cleared your shopping cart! </strong><br>&nbsp;<br></font> </prefix_name:tag_name> 134

Tags with Bodiescore A custom tag can contain custom and

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

1)<tt:lookup id="tx" type="UserTransaction" name="java:comp/UserTransaction" /> <% tx.begin(); %> 2) <tt:define id="book" name="bookDB" /> <jsp:getProperty name="book" property="title">
135

other through shared objects. In the following example, tag1 creates an object called obj1, which is then reused by tag2. <tt:tag1 attr1="obj1" value1="value" /> <tt:tag2 attr1="obj1" /> Also an object created by enclosing tag is available to all inner tags. <tt:outerTag> <tt:innerTag /> </tt:outerTag> 136

Cooperating Tags Custom tags can cooperate with each

Tag Handlersbehavior It is a Java class that implements
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

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

Tag Handlers…

Package javax.servlet.jsp.tagex t
139

Interface Hierarchy

140

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.

Tag

141

void void int int Tag void

Tag – Method summary setPageContext(PageContext pc)
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<abc:simple /> would code A simple tag for example

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 }

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

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 tag Is a utility class to be extended by new
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

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

Method Summary

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

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

Method Summary…

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

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

Class BodyTagSupport

160

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)

Field Summary

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.

BodyContent getBodyContent()

Method Summary…

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

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:

Class TagExtraInfo

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

Classfor a tag in a Tag TagInfo Tag information

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

168

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

Field Summary

  

Method Summary String getTagName()
String getTagClassName() TagExtraInfo getTagExtraInfo() String getBodyContent() String getDisplayName() String getSmallIcon() String getLargeIcon() String getInfoString()
170

The instance (if any) for extra tag information
    

 

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

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

Class TagVariableInfo

174

    

String getNameGiven() String getClassName() boolean getDeclare() int getScope()

Method Summary

String getNameFromAttribute()

175

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.

Class TagAttributeInfo

 

176

Method Summary
   

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

177

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.

Class TagLibraryInfo

178

    

Field Summary protected String tlibversion
protected String jspversion protected String shortname protected String uri protected String info protected TagInfo[] tags
179

   

String getRequiredVersion() String getShortName() String getURI() String getInfoString()

Method Summary

 

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

A simple tag <tt:simple /> 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; } }

Simple tag - Example

187

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

Tagsfor each attribute, the Tag with Attributes In this case

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

The tag <tt:twa attr1="value1"/> has the following TLD attribute element: <name>attr1</name> <required>true</required> <rtexprvalue>true</rtexprvalue>

Attribute Validation using TagExtraInfo

<attribute>

</attribute>

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 for a tag Bodiesis with with body A tag handler
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

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 Does Not Interact with interact with Body If tag handler does not need to

Tag Handler Interacts with Body body, it must If tag handler needs to interact with
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

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…

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: 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.

<body-content>JSP/tagdependent</body-content>

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 variablescreating or A tag handler is responsible for
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

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

Tags with scripting variables

The table below summarizes object scopes.
Name Accessible From
Current page Current and any included or forwarded pages Current request and any subsequent request from same browser (subject to session lifetime)

Lifetime
Until response has been sent back to user or request is passed to a new page Until the response has been sent back to the user Life of user's session

page

request

session

Current and any future application request from the same Web application

Life of the application
200

variable book that is used for accessing book information: <bean:define id="book" name="bookDB" property="bookDetails“ type="database.BookDetails"/> <font color="red" size="+2"> <%=messages.getString("CartRemoved")%> <strong><jsp:getProperty name="book“ property="title"/></strong> <br>&nbsp;<br> </font>
201

Providing Information about Scripting Variable The example below defines a scripting

  

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

Sign up to vote on this title
UsefulNot useful