scwcd 1.4 material

317
SCWCD Material 1 SCWCD Material ©2007 IBM Corporation

Upload: kranthi-kiran

Post on 24-Nov-2014

123 views

Category:

Documents


2 download

TRANSCRIPT

Page 1: SCWCD 1.4 Material

SCWCD Material 1

Author: A. Kranthi KiranEmail: [email protected]

SCWCD Material©2007 IBM Corporation

Page 2: SCWCD 1.4 Material

SCWCD Material 2

Title Page #

SCWCD Material©2007 IBM Corporation

Page 3: SCWCD 1.4 Material

SCWCD Material 3

Web Applications 6 Web Application Structure 6 Web Archive (WAR) 7 Resource Accessibility 8

Servlets 11 Instances of Servlet 11 Servlet Class Loading and Instantiation 12 URL Mappings & Matching 13 Servlet Life Cycle 14

o Other Servlet Methods 15o Exceptions & Life Cycle Methods 16

ServletConfig 16 ServletContext 16

o Configuring context parameters 17 Securing Application Resources 18

HTTP Servlet 19HttpServletRequest 22

o Path information 22o Port Information 23o Information/Messages from client 23

Request Parameters 23 Headers 25 Cookies 28

HttpServletResponse 29o Buffering 29o Information/Messages to Client 29

Headers 30 Cookies 30 OutputStream/Writer 30 Sending Errors/Status Codes 30 Redirecting Response 34

Cookies 35Session 39

Session Maintenance 39 Session Timeout 40 Attributes 41

Request Dispatcher 45 Automatic Attributes 48

Attributes 51 Scopes 51 Attributes & Multi-threading 52 Attributes & Distributed Applications 52

Listeners 54

SCWCD Material©2007 IBM Corporation

Page 4: SCWCD 1.4 Material

SCWCD Material 4

Special Session Related Listeners 57Filters 58

Filter Life Cycle 58 FilterConfig 59 FilterChain 60 Wrapper Classes 60 Application of Filters 60 Filter & Request Dispatcher 64

JSP 66 JspPage and Event Methods 66 HttpJspPage & Service Method 66 URL in JSP 67 Errors & Error Pages 68 Implicit Imports & Objects 69 Attributes & Scopes 71

JSP Elements 73Directives 75

Directive “page” 75 Directive “taglib” 76 Directive “include” 77

Scripting Elements 79 Declarations 79 Scriptlets 79 Expressions 80 Disabling/Enabling scripting elements 80

Standard Actions 81 Runtime Expressions 81 Action <jsp:useBean> 83 Action <jsp:setProperty> 86 Action <jsp:getProperty> 87 Action <jsp:include> 87 Action <jsp:forward> 88 Action <jsp:param> 88 Action <jsp:plugin> 89 Action <jsp:params> 90 Action <jsp:attribute> 90 Action <jsp:body> 91 Action <jsp:element> 92 Action <jsp:text> 93

EL Expressions 95 Usage 95 Operators “[]” and “.” 98 Implicit Objects 100

SCWCD Material©2007 IBM Corporation

Page 5: SCWCD 1.4 Material

SCWCD Material 5

Operators & Precedence 102 Escaping EL Expressions 105 Data Type Conversions 106 Functions 107 Disabling/Enabling EL Expressions 109

Custom Tags 110 TLD File 110 Life Cycle 114

“Classic Tag” Vs “Simple Tag” 115 “Classic Tag” Standard Type 116 “Classic Tag” Iteration Type 117 “Classic Tag” Body Type 118

PageContext 122Types of Custom Tags 127

Tags With Attributes 127 Tags With Body 131 Tags that Define Variables 135 Communication With Parent Tags 143

TryCatchFinallyInterface 146SkipPageException 146Tag Files 147

Packaging of Tag files 147 Tag File Directives 151

Directive “tag” 151 Directive “attribute” 152 Directive “variable” 155

Implicit Objects 157 Tag file Specific Standard Actions 158 Action <jsp:invoke> 158 Action <jsp:doBody> 160

TLD File Structure 162JSP Documents 165

Expressions 167 Directive Standard Actions 168

Action <jsp:directive.page> 168 Action <jsp:directive.include> 168

Scripting Element Standard Actions 169 Action <jsp:directive> 169 Action <jsp:scriptlet> 169 Action <jsp:expression> 169

Other standard Actions 169 Action <jsp:root> 169 Action <jsp:output> 170

SCWCD Material©2007 IBM Corporation

Page 6: SCWCD 1.4 Material

SCWCD Material 6

Core JSTL 172 Action <c:set> 172 Action <c:remove> 174 Action <c:out> 175 Action <c:catch> 176 Action <c:if> 177 Action <c:choose>, <c:when> and <c:otherwise> 178

JSTL Iterator Actions 179 Action <c:forEach> 179 Action <c:forTokens> 183

JSTL URL Related Actions 184 Action <c:import> 184 Action <c:url> 186 Action <c:redirect> 187 Action <c:param> 188

Security 189 Security Mechanisms 189 Realm 190 Authentication 191 Authorization 194 Data integrity & Confidentiality 197 Programmatic Security 198

J2EE Patterns 200 Model View Controller 200 Intercepting Filter 203 Front Controller 204 Service Locator 205 Business Delegate 207 Transfer Object 209

Deployment Descriptor 212 Application Level Properties 214 Filter Related Properties 216 Servlet Related Properties 218 JSP Related Properties 220 Security Related Properties 221 Environment Related Properties 223 EJB Related Properties 224 JMS Related Properties 226 Web services Related Properties 227 Other Properties 227

Last Minute Notes 229

SCWCD Material©2007 IBM Corporation

Page 7: SCWCD 1.4 Material

SCWCD Material 7

Web Applications

A “Web Application” as the name suggests, is the application that serves web requests which runs in a container. A “Web Application” should exist as structured hierarchy of directories. The root of the web application serves as document root for the web application.

A Web container provides services like request dispatching, security, concurrency, and life-cycle management.

Web-Application Structure

/WEB-INF Directory: This directory (and its sub-directories) contains files/resources used by the web application internally and these resources will not be accessible to the client applications.

SCWCD Material©2007 IBM Corporation

WEB Application

WEB-INF(web.xml)

classes

lib

META-INF

tags(*.tag , *.tagx)

Other files….(JSP files, HTML Files etc)

Page 8: SCWCD 1.4 Material

SCWCD Material 8

The resources in this directory can be accessed using getResource() or getResourceAsStream() on ServletContext. These resources can be exposed using ResourceDispatcher (Check for more details “Securing application resources” section).

Deployment Descriptor: Deployment descriptor (web.xml) of the web application should be placed in WEB-INF directory. (/WEB-INF/web.xml).“/WEB-INF/classes” Directory: This directory will contain the classes that can be used by the application. This may include servlet classes also.“/WEB-INF/lib” Directory: This directory contains JAR archive files with “jar extension” (*.jar). Which can contain classes or resources that can be used by the application.“WEB-INF/tags” Directory: This directory should contain JSP tag extension files (*.tag or *.tagx). The other place where tag extension files can be present is in “/META-INF/tags/” directory of JAR files placed in “/WEB-INF/lib” directory. Tag extension files appearing in any other locations will not be considered as tag extensions.

The other important files /WEB-INF directory will contain is TLD (Tag library Descriptor) files.

/META-INF Directory: This directory contains useful information needed by the JAR tools.

Other files: The root (and its sub-directories other than WEB-INF, META-INF) of the application itself will contain other web application files (which are directly accessible to clients) such as JSP, HTML, Images (etc).

Web Achieve (WAR)

WAR stands for “Web Achieve” and is nothing but a JARed version of the web-application directory structure. And WAR can be constructed using JAR command. For example consider an application “payroll” in “c:\payroll” with following sub-directories and files:

\payroll\index.htmllogin.jsp

\payroll\pagesemployee.jspmanager.jsp

\payroll\imageslogo.gifleft-nav.gif

\payroll\WEB-INFweb.xml

SCWCD Material©2007 IBM Corporation

Page 9: SCWCD 1.4 Material

SCWCD Material 9

\payroll\WEB-INF\classes\com\payroll\servlets

LoginServlet.classEmployee.class

\payroll\WEB-INF\libPOI.jarreports.jar

For the above application a WAR file can be built using command:C:\payroll> JAR cvf payroll.war .

Resource Accessibility

In a web application resources can be accessed in two ways:

1. Using ServletContext: Any resource present (directly, without sub-jaring) in the web application can be accessed.

2. Using ClassLoader: Resources present in /WEB-INF/classes directory and present in JAR files of /WEB-INF/lib directory can be accessed.

When searching for a class, container first looks into /WEB-INF/classes then into /WEB-INF/lib JAR files.

Following example illustrates how resources in different location of the web-applications can be accessed using ServletContext and ClassLoader (and which are not accessible).

ServletContext context=getServletContext();ClassLoader loader=this.getClass().getClassLoader();InputStream is=null;

//Accessing resources using ServletContextSystem.out.println("Resources accessible from ServletContext: ");

is=context.getResourceAsStream("/rootRes.res");System.out.println("\tResource in web-app root (/rootRes.res) is accesible: "+(is!=null));

is=context.getResourceAsStream("/WEB-INF/webInfRes.res");System.out.println("\tResource in WEB-INF (/WEB-INF/webInfRes.res) is accesible: "+(is!=null));

is=context.getResourceAsStream("/WEB-INF/classes/classRes.res");System.out.println("\tResource in WEB-INF/classes (/WEB-INF/classes/classRes.res) is

SCWCD Material©2007 IBM Corporation

Page 10: SCWCD 1.4 Material

SCWCD Material 10

accesible: "+(is!=null));

is=context.getResourceAsStream("/WEB-INF/lib/libRes.res");System.out.println("\tResource in WEB-INF/lib (/WEB-INF/lib/libRes.res) is accesible: "+(is!=null));

is=context.getResourceAsStream("/META-INF/metaInfRes.res");System.out.println("\tResource in META-INF (/META-INF/metaInfRes.res) is accesible: "+(is!=null));

//Accessing resources using ClassLoaderSystem.out.println("\nResources accessible from Class Loader: ");

is=loader.getResourceAsStream("/rootRes.res");System.out.println("\tResource in web-app root (/rootRes.res) is accesible: "+(is!=null));

is=loader.getResourceAsStream("/webInfRes.res");System.out.println("\tResource in WEB-INF (/WEB-INF/webInfRes.res) is accesible: "+(is!=null));

is=loader.getResourceAsStream("/classRes.res");System.out.println("\tResource in WEB-INF/classes (/classRes.res) is accesible: "+(is!=null));

is=loader.getResourceAsStream("/WEB-INF/lib/libRes.res");System.out.println("\tResource in WEB-INF/lib (/WEB-INF/lib/libRes.res) is accesible: "+(is!=null));

is=loader.getResourceAsStream("/META-INF/metaInfRes.res");System.out.println("\tResource in META-INF (/META-INF/metaInfRes.res) is accesible: "+(is!=null));

Output:Resources accessible from ServletContext:

Resource in web-app root (/rootRes.res) is accesible: trueResource in WEB-INF (/WEB-INF/webInfRes.res) is accesible: trueResource in WEB-INF/classes (/WEB-INF/classes/classRes.res) is accesible:

trueResource in WEB-INF/lib (/WEB-INF/lib/libRes.res) is accesible: trueResource in META-INF (/META-INF/metaInfRes.res) is accesible: true

Resources accessible from Class Loader: Resource in web-app root (/rootRes.res) is accesible: falseResource in WEB-INF (/WEB-INF/webInfRes.res) is accesible: falseResource in WEB-INF/classes (/classRes.res) is accesible: trueResource in WEB-INF/lib (/WEB-INF/lib/libRes.res) is accesible: falseResource in META-INF (/META-INF/metaInfRes.res) is accesible: false

SCWCD Material©2007 IBM Corporation

Page 11: SCWCD 1.4 Material

SCWCD Material 11

Accessing resources from client application

Assuming the web-application is running in local host, following table illustrated the resources accessibility from the client

http://localhost:8080/scwcd/rootRes.res Accessiblehttp://localhost:8080/scwcd/WEB-INF/webInfRes.res

“404” Error

http://localhost:8080/scwcd/META-INF/metaInfRes.res

“404” Error

SCWCD Material©2007 IBM Corporation

Page 12: SCWCD 1.4 Material

SCWCD Material 12

Servlets

A servlet is a JavaTM technology-based Web component, managed by a container that generates dynamic content. Like other Java technology-based components, servlets are platform-independent Java classes that are compiled to platform-neutral byte code that can be loaded dynamically into and run by a Java technology-enabled Web server.

Actually “Web Server” (like Apache) is only capable of receiving HTTP request and sending HTTP responses with the help of static content. It’s the container (like Tomcat) which actually can communicate with Servlet and offers lot of special services and serves the dynamic content to web server which is in turn sent back to client.

Tomcat by itself is a container but can act like a “Web Server” but not as a robust one like Apache.

A fully complaint J2EE server should have Web container, EJB container and support other services like JNDI, connection pooling, JMS etc.

The servlet container (part of a Web server or application server) holds/provides following responsibilities/services:

Network services over which requests and responses are sent Decodes MIME-based requests and formats MIME-based responses. Servlet life cycle management Multi-threading support for serving requests concurrently. Declarative security. JSP support

A Servlet is a class which implements interface javax.servlet.Servlet directly/indirectly.

Instances of Servlet

In a web application, only one instance of Servlet is maintained and the service() method is called on this single instance in multiple threads to serve request concurrently.

For distributed web-application (by default, all web applications are non-distributed) single instance of Servlet is maintained per JVM. Thus in either case (distributed and non-distributed) only one Servlet instance is maintained per JVM.

SCWCD Material©2007 IBM Corporation

Page 13: SCWCD 1.4 Material

SCWCD Material 13

For servlets which implement javax.servlet.SingleThreadModel interface (deprecated) container may create new instance for every new request. In fact, SingleThreadModel guarantees that at any given time only one thread will execute give servlet instance’s service() method.

Servlet class loading and instantiation

The servlet container is responsible for loading and instantiating servlets. The loading and instantiation can occur when the container is started, or delayed until the container determines the servlet is needed to service a request.

Configuring Servlet

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4">…………………………………

<servlet><description>Simple Test Servlet</description><display-name>TestServlet</display-name>

<servlet-name>TestServlet</servlet-name> <!-- Name of Servlet --><!-- Name of servle class --><servlet-class>com.test.TestServlet</servlet-class>

<!-- Init parameters for servlet --><init-param>

<description>Name of the user</description><param-name>name</param-name><param-value>kranthi</param-value>

</init-param><init-param>

<description>password</description><param-name>password</param-name><param-value>pop</param-value>

</init-param></servlet>

<!-- Mapping servlet to url pattern --><servlet-mapping>

<servlet-name>TestServlet</servlet-name><url-pattern>/test</url-pattern>

</servlet-mapping>………………………….

SCWCD Material©2007 IBM Corporation

Page 14: SCWCD 1.4 Material

SCWCD Material 14

…………………………</web-app>

URL Mappings & Matching

Following are the rules for defining URL patterns for the servlets:

1. Exact Match : This type of patterns should start with “/” and should contain only static text and can end with extension.

Example: /bank/employee/addEmployee.do

2. Directory Match : This must start with a “/” and should end with “*”.Example: /bank/employee/*

3. Extension Match : This must start with “*.” And should specify some extension.Example: *.do

4. Default Servlet : URL pattern for this is going to be just “/”.

Container will follow the below approach to map URL to servlet/resource:1. Container will look for matches in following sequence- “Exact Match”,

“Directory Match”, “Extension Match”. If nothing is found then default servlet will be used.

2. If multiple “Directory Matches” are found, then the container chooses the longest mapping. For example, /bank/employee/addEmployee.do container will choose URL-pattern /bank/employee/* instead of /bank/*.

The container will use case-sensitive string comparisons for matching.

Note: If the container has internal JSP container, then JSP will be mapped to it. But the application configuration will be taken higher precedence. Sometimes container may have implicit mapping (for example displaying the contents of directory matching with the request URL).

Remember container will go to JSP files (or any other static content) only if no URL pattern match is matching.

Examples: If following URLs are configured in an application

/list/test/*/list/test/test/*

SCWCD Material©2007 IBM Corporation

Page 15: SCWCD 1.4 Material

Init

Service

Destroy

SCWCD Material 15

Then for request URL “/<context>/list/test/test/pop” second one will be used because of its longest match.

If a default servlet (having URL pattern “/”) is configured, then container will never go to any static content directly.

Servlet Life Cycle

The life-cycle of the Servlet consists of following three steps in the below sequence:

1. Initialization : The servlet is initialized by calling init() method of servlet. The call to this method indicates the servlet is going to be placed for service. And this method is called only once and expected to initialize the resources needed by the servlet.

If this method (init()) throws SevletException or doesn’t return in time defined by web server, then the servlet will not used for service. For every request servlet’s init() method will be called till it gets completed properly.

2. Service : For each request made by the user, to the mapping resource(s), the service() method of the servlet will get called by “Servlet Container”. This method might be called in multiple threads to serve multiple requests simultaneously; so shared resource access should be synchronized properly.

Status code should be set to the response, if the servlet throws or sends an error.Note: sevice() method will be called only if init() method is completed properly.

3. Destroy : “Servlet Container” will call destroy() method of the servlet to indicate, that the servlet is being removed out of service. After this method service() method will not be called on this servlet.

Container may choose to remove servlet from service for many reasons (for example memory cleanup). After destroy() is called on a servlet instance even if a new request is made for this servlet, this instance will not be used. Instead container will create new instance and initialize it and then call service() method over it.

This method is expected to release/cleanup the resources this servlet is holding. Before the servlet container calls the destroy method, it will allow any threads that are currently running in the service method of the servlet to complete execution, or exceed a server-defined time limit. After the destroy method

SCWCD Material©2007 IBM Corporation

Page 16: SCWCD 1.4 Material

SCWCD Material 16

completes, the servlet container will release the servlet instance so that it is eligible for garbage collection.

Other Servlet Methods

In addition to the life-cycle methods, this interface provides the getServletConfig method, which the servlet can use to get any startup information, and the getServletInfo method, which allows the servlet to return basic information about itself, such as author, version, and copyright.

public class LifeCycleTest extends GenericServlet{

public void destroy(){

super.destroy();System.out.println("Destroy method is called.....");

}

public void init(ServletConfig config) throws ServletException{

super.init(config);System.out.println("Init method is called....");//throw new ServletException("Exception from init method....");

}

public void service(ServletRequest req,ServletResponse res) throws ServletException,IOException

{String param=req.getParameter("excep");

if("true".equals(param))throw new ServletException("Exception is service method....");

res.getWriter().print("Response from life cycle test servlet for parameter: "+param);

}

public String getServletInfo(){

System.out.println("getServletInfo() is called....");return super.getServletInfo();

SCWCD Material©2007 IBM Corporation

Page 17: SCWCD 1.4 Material

SCWCD Material 17

}}

Exceptions and Life Cycle Methods

init() method: If init() method throws an exception, then service() method will never get called. Instead init() method will be called every time a request is made for that particular servlet till it get completed normally.

service() method: Even if service() method throws an exception, it will not restrict/stop the next request to the same servlet.

UnavailableException: A servlet service() method should throw UnavailableException if the servlet is temporarily/permanently unavailable. This may be due to multiple reasons, such as the servlet is unable to connect to third tier, some configuration problem. In the constructor of the UnavailableException we can specify the time servlet may be unavailable.

If permanent unavailability is indicated container may remove this servlet from service by calling destroy() method. And any further request this servlet will return error. Container may treat temporary unavailability as a permanent one.

UnavailableException(String msg, int seconds)

ServletConfig

The instance of ServletConfig passed to the init() method will be helpful in retrieving following information:

1. Current servlet init parameter list and their values.String getInitParameter(String paramName)Enumeration getInitParameterNames()

2. Name of the servlet as defined in web.xml, if not defined, it will be servlet class name.

String getServletName()

3. Getting reference to the current ServletContext.ServletContext getServletContext()

SCWCD Material©2007 IBM Corporation

Page 18: SCWCD 1.4 Material

SCWCD Material 18

ServletContext

ServletContext represents the servlet view of the application in which the servlet is running. In distribute applications every JVM will have its own ServletContext instance for this application. ServletContext provides following services:

1. Access to context initialization parameters: getInitParameter(), getInitParameterNames()

2. Attributes in application scope: setAttribute(), getAttribute(), removeAttribute(), getAttributeNames()

3. Accessing Resources: getResource(), getResourceAsStream()

4. Temporary Directory: Container provides a unique temporary directory for each web application context. This can be accessed using context attribute “javax.servlet.context.tempdir” whose type is java.io.File.

Since multiple context instance exists in distributed applications (one per JVM), distributed applications should not use “context attributes” for sharing information.

Configuring Context parameters

Following code shows how we can configure context parameters and how to access them.

<web-app xmlns="http://java.sun.com/xml/ns/j2ee">…………..……………

<context-param><description>Global user</description><param-name>global</param-name><param-value>global</param-value>

</context-param>

<context-param><description>Password for global user</description><param-name>globalPassword</param-name><param-value>pip</param-value>

</context-param>…………..…………..</web-app>

SCWCD Material©2007 IBM Corporation

Page 19: SCWCD 1.4 Material

SCWCD Material 19

ServletContext context=getServletContext();

out.println("Global \"Name\": "+context.getInitParameter("global"));

out.println("Global \"Password\": "+context.getInitParameter("globalPassword"));

Note: While configuring in web.xml we use name <context-param> while retrieving this value we use method getInitParameter()

Securing Application Resources

Resources present in WEB-INF and META-INF directories can not be accessed by clients directly. But these resources can be accessed using RequestDispatcher. Thus secured resources can be kept in WEB-INF or META-INF directory and can be accessed using RequestDispatcher from servlet after proper authentication.

protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,

IOException {

RequestDispatcher rd=req.getRequestDispatcher("/META-INF/test.txt");rd.forward(req,res);

}

SCWCD Material©2007 IBM Corporation

Page 20: SCWCD 1.4 Material

SCWCD Material 20

HTTP Servlet

HTTP Servlet (javax.servlet.hhtp.HTTPServlet) is an abstract implementation of Servlet (javax.servlet.Servlet) (actually extension of javax.servlet.GenericServlet) and represents a servlet, which can take Http request and provide Http response.

In order to serve different kind of HTTP methods, multiple methods are defined in HTTPServlet class, which is described below.

Note service(ServletRequest, ServletResponse) calls service(HttpServletRequest, HttpServletResponse) which in turn calls doXXX() methods depending on the request type.

HTTP Method

(doXXX() of HttpServlet

Clas)

Description

OPTIONS(doOptions())

The OPTIONS method represents a request for the list of services provided by Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating resource retrieval.

Depending on the overridden list of methods, this method will return headers about the services this servlet can provide. Thus in general (unless new HTTP methods are added), this method need not be overridden.

GET(doGet())

The GET method means retrieves whatever information (in the form of an entity) is identified by the Request-URI. This method is not expected to modify any information on server, it is just expected to retrieve information.

GET method (browser) may define condition using headers If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range. Depending on this header information, server is expected return the data (generally only if it is modified). If resource is not modified (as per response status) then the browser

SCWCD Material©2007 IBM Corporation

Page 21: SCWCD 1.4 Material

SCWCD Material 21

will use its own or proxy cache to display the page. This will improve performance by reducing unnecessary data transfer.

The doService() method of HttpServlet will take care of conditional-GET with the help of return value of getLastModified() method. Thus whenever possible getLastMoidified() method should be overridden appropriately.

By default getLastModified() returns –1 indicating unknown modification time.

GET should not be used for critical information (like passwords, credit card #) because information will get appended to the URL (as query string). And browsers and proxies generally cache URLs. Since information is appended to URL the length of information that can be sent is limited.

Since the form data is part of URL (as query string) pages using GET method (like google) can be bookmarked.

HEAD(doHead())

HEAD method expects the server to send the header information of the request URI, which should be identical to the headers that would be set by GET method. This method can be used for obtaining metainformation about the entity implied by the request without transferring the entity-body itself. This method is often used for testing hypertext links for validity, accessibility, and recent modification.

The doHead() method of HttpServlet will in turn calls doGet() method and uses the content (which will not be sent to client) to accurately calculate the content length and sets it Content-Length header of response. For better performance this method should be overridden and return appropriate header information.

POST(doPost())

POST method is used to send information (unlimited) submitted by forms, to update database, to post message to bulletin, news group etc. The information is sent to the server as part of the request body.

Generally browser or proxies will not cache responses to these requests. Unless the response includes appropriate Cache-Control or Expires header fields.

This method generally updates the server side data.

If not overridden this method will send an error to the client, indicating this method is not supported.

Since the form data is not part of URL (like GET) pages using POST can not be bookmarked,

PUT(doPUT())

PUT method is used to put/update the resource identified by specified URI on the server.

The URI in a POST request identifies the resource that will handle the enclosed

SCWCD Material©2007 IBM Corporation

Page 22: SCWCD 1.4 Material

SCWCD Material 22

entity. Whereas the URI in a PUT request identifies the entity enclosed with the request.

If not overridden this method will send an error to the client, indicating this method is not supported.

DELETE(doDelete())

The DELETE method requests that the origin server delete the resource identified by the Request-URI.

The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.

If not overridden this method will send an error to the client, indicating this method is not supported.

Operations requested through DELETE can have side effects for which users can be held accountable. When using this method, it may be useful to save a copy of the affected URL in temporary storage.

TRACE(doTrace())

The TRACE method is used to invoke a remote, application-layer loop- back of the request message. The final recipient of the request SHOULD reflect the message received back to the client as the entity-body of a 200 (OK) response. If the request is valid, the response SHOULD contain the entire request message in the entity-body, with a Content-Type of "message/http". Responses to this method WILL NOT be cached.

The doTrace() method HttpServlet will take care of this functionality. There is no need to override this file.

For POST method

Set the headers before writing to the OutputStream/Writer of response. Because response headers should be sent before sending the body.

Its always preferred to set headers like content-type (setContentType()), content-length (setContentLength()), encoding (setCharacterEncoding()) etc.

Note: getMethod() of HttpRequest will tell the method used in sending the request. For example, the return value would be GET, POST, etc.

The default method used to get a resource (when URL is fed) is GET method.

POST & DELETE are the only non-idempotent (need not be always) HTTP methods.

SCWCD Material©2007 IBM Corporation

Page 23: SCWCD 1.4 Material

SCWCD Material 23

Idempotent methods are the one which can be repeated safely, which is possible only if state is not changed on server

GET, HEAD, OPTIONS, TRACE & PUT are idempotent by nature. Its up to applications to maintain this behavior. Note PUT even though changes server state, it can be repeated safely.

The only HTTP method missing (like doXXX()) in HttpServlet is CONNECT. This method is used for tunneling.

HttpServletRequest

For every request made by the client a new Request instance is created. This instance is meant only for this thread. Application has to make sure that request instances are accessed only in their corresponding threads, otherwise results are ambiguous (because sometimes container may recycle the request objects for the sake of performance).

Path Information

A request object provides following information:

Context Path: The path prefix associated with the ServletContext that this servlet is a part of. If this context is the “default” context rooted at the base of the Web server’s URL name space, this path will be an empty string. Otherwise, if the context is not rooted at the root of the server’s name space, the path starts with a ‘/’ character but does not end with a ‘/’ character.

This value can be accessed using method getContextPath().

Servlet Path: The path section that directly corresponds to the mapping which activated this request. This path starts with a’/’ character except in the case where the request is matched with the ‘/*’ pattern, in which case it is an empty string.

This value can be accessed using method getServletPath()

PathInfo: The part of the request path that is not part of the Context Path or the Servlet Path. It is either null if there is no extra path, or is a string with a leading ‘/’.

This value can be accessed using method getPathInfo()

Consider following application setup

SCWCD Material©2007 IBM Corporation

Page 24: SCWCD 1.4 Material

SCWCD Material 24

Context Path /catalog

Servlet Mapping Pattern: /lawn/*Servlet: LawnServlet

Servlet Mapping Pattern: /garden/*Servlet: GardenServlet

Servlet Mapping Pattern: *.jspServlet: JSPServlet

Request Path Path Elements/catalog/lawn/index.html ContextPath: /catalog

ServletPath: /lawnPathInfo: /index.html

/catalog/garden/implements/ ContextPath: /catalogServletPath: /gardenPathInfo: /implements/

/catalog/help/feedback.jsp ContextPath: /catalogServletPath: /help/feedback.jspPathInfo: null

Port Information

From the request object we can get three types of port information their details are as follows:

getRemotePort(): Returns the client machine port number from which request has been made to server.

getServerPort(): The port on server to which the request has been sent. getLocalPort(): The port at which request is being served. This may be different

from getServerPort() because, server may turn around the request to other port so that multiple requests can be served concurrently.

Information/Messages from Client

The data can be received from client through request in following forms: Request Parameters Headers Cookies

Note, Even though ServletRequest provides methods like getInputStream() and getReader(), this will be of no use for HttpServletRequest. The content will be always empty.

SCWCD Material©2007 IBM Corporation

Page 25: SCWCD 1.4 Material

SCWCD Material 25

Request Parameters

Following is the list of methods available in HttpRequest to access request parameters.

Enumeration getParameterNames()String getParameter(String name)Map getParameterMap()String[] getParameterValues()

Request parameters are nothing but the name-value pairs representing the form fields, which submitted the request to the current servlet. Fields with same name will represent array of values and for such fields getParameterValues() should be used.

If getParameter() is used for multi-values parameter only first value will be returned. And if getParameterValues() is used for single-valued parameter then an array of length 1, having the single value, will be returned.

In the Map returned by getParameterMap(), parameter names are keys and values are String arrays.If the parameters are passed both using query string (like GET method) and using POST method, then the parameters specified in the query string will be included first, then the values from POST.

Servlet Code : out.println("<H1>Parameters</H1><BR>");out.println("<TABLE><TR><TH>Name</TH><TH>Value</TH>");e=req.getParameterNames();

while(e.hasMoreElements()){

name=(String)e.nextElement();out.println("<TR><TD>");out.println(name);out.println("</TD><TD>");//Assuming field name ending with “s” represents

// multiple fields with same name (Array of Values)if(name.endsWith("s")){

values=req.getParameterValues(name);for(int i=0;i<values.length;i++)

out.println(values[i]+" , ");}else{

value=req.getParameter(name);

SCWCD Material©2007 IBM Corporation

Page 26: SCWCD 1.4 Material

SCWCD Material 26

out.println(value);}

out.println("</TD></TR>");}

out.println("</TABLE>");

HTML Code

<FORM ACTION="reqTest?hparams=100&hparams=200" name="form1" method="POST">FName: <INPUT TYPE="text" NAME="FName" VALUE="Kranthi"/><BR>LName: <INPUT TYPE="text" NAME="LName" VALUE="Kiran"/><BR>Age: <INPUT TYPE="text" NAME="Age" VALUE="26"/><BR>Address: <INPUT TYPE="text" NAME="Add" VALUE="XXXX, xxx,xxx"/><BR><!— Multi-valued field --><INPUT TYPE="hidden" NAME="hparams" VALUE="1"/><INPUT TYPE="hidden" NAME="hparams" VALUE="2"/><INPUT TYPE="hidden" NAME="hparams" VALUE="3"/>

<INPUT TYPE="Submit" value="Submit"/></FORM>

OutputParameters

Name ValueFName Kranthi Add XXXX, xxx,xxx LName Kiran hparams 100 , 200 , 1 , 2 , 3 , Age 26

Note: Request parameter names are case sensitive.

Headers

Enumeration getHeaderNames()String getHeader(String name)long getDateHeader(String name)int getIntHeader(String name)

SCWCD Material©2007 IBM Corporation

Page 27: SCWCD 1.4 Material

SCWCD Material 27

Enumeration getHeaders(String name)

Similar to request parameters, headers can also have multiple values. And getHeader() for multi-valued header will return first head and getHeaders() for single-values header will return enumeration of size 1.

Note, cookies are sent to server from client in the single-valued (using semicolon (;) as delimiter) request header under name “cookie”.

Servlet Code

out.println("<H1>Headers</H1><BR>");out.println("<TABLE><TR><TH>Name</TH><TH>Value</TH>");e=req.getHeaderNames();

while(e.hasMoreElements()){

name=(String)e.nextElement();out.println("<TR><TD>");out.println(name);out.println("</TD><TD>");

if(name.endsWith("s")){

eValues=req.getHeaders(name);for(int i=0;eValues.hasMoreElements();i++)

out.println(eValues.nextElement()+" , ");}else{

value=req.getHeader(name);out.println(value);

}out.println("</TD></TR>");

}out.println("</TABLE>");out.println("</BODY></HTML>");

SCWCD Material©2007 IBM Corporation

Page 28: SCWCD 1.4 Material

SCWCD Material 28

Output

accept image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*

referer http://localhost:8080/scwcd/reqTest.jsp accept-language

en-us

content-type application/x-www-form-urlencoded accept-encoding

gzip, deflate

user-agent Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1) host localhost:8080 content-length

84

connection Keep-Alive cache-control

no-cache

cookie name=kranthi; age=kiran; language=english; JSESSIONID=E0837AE735382D624167BB69A4FB2451

Note: Unlike request parameters, request header names are case insensitive.

In HTML headers can be sent to server using <META> element.

<HTML><HEAD>

<META HTTP-EQUIV="Header1" CONTENT="Value1"><META HTTP-EQUIV="Header2" CONTENT="Value2"><META HTTP-EQUIV="Header3" CONTENT="Value3">

</HEAD><BODY>

<a href="dispHead">Display Headers</a></BODY>

</HTML>

But above code is not working, but as per HTML specification above code should work. Tested with TOMCAT 5.0

SCWCD Material©2007 IBM Corporation

Page 29: SCWCD 1.4 Material

SCWCD Material 29

Cookies

Cookie[] getCookies()

Note, cookies are sent to server from client in the multi-valued request header under name “cookie”.

Cookies are discussed in detail in coming section titled “Cookies”.

SCWCD Material©2007 IBM Corporation

Page 30: SCWCD 1.4 Material

SCWCD Material 30

HttpServletResponse

For every request made by the client a new Response instance is created. This instance is meant only for this thread. Applications has to make sure that response instances are accessed only in their corresponding threads, otherwise results are ambiguous (because sometimes container may recycle the response objects for the sake of performance).

Buffering

Almost all containers provide buffering capability to the response. Following is the list of methods related to buffering:

getBufferSize(): Gets the buffer size of this response.

setBufferSize(): Sets the buffer size of the response. The resultant size may be greater (so that the same buffer can be reused by container) than the specified size. This will throw exception if response is already committed.

isCommitted(): Returns true if response is already committed. That is if buffer contents are flushed to client partly or completely.

reset(): Clears the buffer contents, headers and status codes. This will throw exception if response is already committed.

resetBuffer(): Clears buffer contents alone. This will throw exception if response is already committed.

flushBuffer(): Flushes buffer contents to the client and commits the response.

Information/Messages to Client

The information/messages from the server to client can be sent in following ways:

Headers Cookies OutputStream/Writer Error Messages & Status Codes

SCWCD Material©2007 IBM Corporation

Page 31: SCWCD 1.4 Material

SCWCD Material 31

Headers

For successful transmission headers should be set before response is committed. Headers setting/adding after response is committed will be ignored by container.

Headers can be sent to client using following methods. Some convenient methods are added to add common headers to response.

addHeader(String name, String value)addIntHeader(String name, int value)addDateHeader(String name, long value)setHeader(String name, String value)setIntHeader(String name, int value)setDateHeader(String name, long value)boolean containsHeader(String name)

setContentType(String type)setContentLength(int len)setCharacterEncoding(String encoding)

Adders are used to set multi-valued headers whereas setters are used to set single-valued headers. Setter version of headers will replace current header value (if existing).

Before writing anything to response object it is preferred to set content type (like “text/html”). For static resources MIME-extension mapping present in web.xml can be used.

Headers/Cookies will not be visible in the output HTML source code. Because, response headers/cookies are something sent by server and expected to be processed by client. And HTML headers/cookies are the one, which will be sent by client to server as the part of request.

A response object looks as shown in the figure. The headers part will be processed by browser and “HTML source” will not contain header information.

Cookies

Cookies can be added using following methods:addCookie(Cookie cookie)

SCWCD Material©2007 IBM Corporation

Page 32: SCWCD 1.4 Material

SCWCD Material 32

OutputStream/Writer

The output stream /Writer can be obtained using following methods:

ServletOutputStream getOutputStream()PrintWriter getWriter()

Note: ServletOutputStream defines convenient methods of print() and println() methods for all primitives and String values.

res.addHeader("Authors","Kranthi");res.addHeader("Authors","Kiran");res.addHeader("Authors","Tiger");

res.addIntHeader("IDS",100);res.addIntHeader("IDS",200);res.addIntHeader("IDS",300);

res.addDateHeader("res_date",3000);

res.setHeader("testHead","val1");res.setHeader("testHead","val2");

res.setContentType("test/html");res.setContentLength(500);

res.addCookie(new Cookie("name","kranthi"));res.addCookie(new Cookie("age","kiran"));res.addCookie(new Cookie("language","english"));

PrintWriter out=res.getWriter();out.println("<HTML><HEAD><title>Http Response Testing....</title></HEAD><BODY>");out.println("<B>Test output......</B>");out.println("</BODY></HTML>");out.close();

Sending Errors & Status Codes

Errors can be sent to client using following methods:sendError(int sc)sendError(int sc,String mssg)

SCWCD Material©2007 IBM Corporation

Page 33: SCWCD 1.4 Material

SCWCD Material 33

sendError() will discard all the content of response, without altering headers/cookies and sends the error message to client. If the response is already committed this methods will throw IllegalStateException.

Note: The response can get committed in multiple ways – by closing the Writer/OutputStream obtained from response, using sendRedirect(), sendError().

Output of res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

Output of res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Simple Error message from server...");

SCWCD Material©2007 IBM Corporation

Page 34: SCWCD 1.4 Material

SCWCD Material 34

Note: If an error-page declaration has been made for the web application (in web.xml) corresponding to the status code passed in, it will be served back in preference to the suggested msg parameter.

Usage of sendError() will commit the response.

Status Codes

Status codes are one more way of sending information to the client. This will not have any effect on output in general.

PrintWriter out=res.getWriter();out.println("<HTML><HEAD><title>Http Response

Testing....</title></HEAD><BODY>");out.println("<B>Test output......</B>");out.println("</BODY></HTML>");

res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);

O/P:

Test output......

SCWCD Material©2007 IBM Corporation

Page 35: SCWCD 1.4 Material

SCWCD Material 35

Redirecting Response

A response can be redirected to other page using sendRedirect().

sendRedirect() takes URL as parameter. If the URL starts with “/” the URL is considered to be from container root (excluding context root) otherwise it is considered as relative URL.

sendRedirect() will throw IllegalStateException if the response is already committed. And the call to this method will commit the response.

Note, sendRedirect() will make the client to redirect to new URL, its not like forwarding the request to new URL. Remember, we are sending response, asking client to redirect to different URL, unlike forwarding request itself to other page.

We can specify even absolute URL in sendRedirect(). But note it should start with “http://” or other protocol. For example if “google.com” is specified, it will be treated as relative URL.

res.sendRedirect(res.encodeRedirectURL("/scwcd/reqTest.jsp"));

res.sendRedirect("http://google.com");

Note: In the browser URL also gets changed.

Method encodeRedirectURL() will check if the session-id needs to be encoded in the URL and modifies the URL appropriately. If this is not used and session is maintained using URL rewriting then the URL will become inappropriate.

SCWCD Material©2007 IBM Corporation

Page 36: SCWCD 1.4 Material

SCWCD Material 36

Cookies

A Cookie (javax.servlet.http.Cookie) is small information sent by the server to the client, which gets cached and are resent to the server depending on the cookies attributes. A cookie can be created using only constructor available

Cookie(String name, String value)A cookie supports following properties. All these properties have both setters and getters except Name (only getter is available):

Property Type Optional CommentsName String No Name of the cookie. This is only immutable property of

Cookie class. This value is specified in the constructor.Value String No Value for the cookie. If the value is binary BASE64

encoding should be used.Comment String Yes A comment. This will be useful if the browser presents

cookie to the user.Domain String Yes Domain in which sookie should be presented.

Domain name should start with a dot (.foo.com) and means that the cookie is visible to servers in a specified Domain Name System (DNS) zone (for example, www.foo.com, but not a.b.foo.com). By default, cookies are only returned to the server that sent them.

MaxAge int Yes Maximum age of cookie in seconds.

Negative Value: Cookie will be deleted once browser exits.Zero Value: Cookie will be deleted immediately.Positive Value: Cookie will be deleted after specified number of seconds.

Path String Yes Cookie will be visible for all the pages under directory specified by “Path”. “Path” should include the directory that created this cookie.

Secure boolean Yes Says whether the browser should send this cookie only through secured protocol like HTTPS, SSL.

Default value is false.Version int Yes Sets the version of the cookie protocol this cookie

complies with. 0 if the cookie should comply with the original Netscape specification; 1 if the cookie should comply with RFC 2109.

SCWCD Material©2007 IBM Corporation

Page 37: SCWCD 1.4 Material

SCWCD Material 37

Currently 0 is the only preferred version.Some browser does not work properly with optional attributes.

Server sends cookies to client as response header and browser resents the cookies to the server as request header (single-valued with name “cookie” using semi-colon (;) as delimiter).

The following code shows a servlet code, which sends cookies with different attributes as shown below in the code. This servlet is configured under URL pattern “/scwcd/cookie/test/addCookies” (scwcd is the root name).

Cookie zeroAged=new Cookie("zero-aged","Zero Aged");zeroAged.setMaxAge(0);res.addCookie(zeroAged);

Cookie negAged=new Cookie("neg-aged","Negative Aged");negAged.setMaxAge(-100);res.addCookie(negAged);

Cookie posAged=new Cookie("pos-aged","Positive Aged");posAged.setMaxAge(Integer.MAX_VALUE);res.addCookie(posAged);

Cookie cmt=new Cookie("commented","Commented");cmt.setComment("Simply commented cookie...");res.addCookie(cmt);

Cookie pth=new Cookie("pathCookie","Path");pth.setPath("/scwcd/cookie/");res.addCookie(pth);

res.getWriter().print("Cookies additon completed.....");

The following is the output when header “cookie” and all the available cookies are displayed under URL “/scwcd/cookie/dispCookies”

SCWCD Material©2007 IBM Corporation

Page 38: SCWCD 1.4 Material

SCWCD Material 38

cookie neg-aged="Negative Aged"; pos-aged="Positive Aged"; commented=Commented;

Cookies

Name Value Comment Domain Max Age Path Secure Versionpos-aged "Positive Aged" null null -1 null false 0 neg-aged "Negative Aged" null null -1 null false 0 commented Commented null null -1 null false 0 pathCookie Path null null -1 null false 0

Note: Zero aged cookie (With MaxAge 0 value) is missing.

Following is the output when header “cookie” and all cookies are displayed using URL (/scwcd/cookie)

cookie pathCookie=Path

Cookies

Name Value Comment Domain Max Age Path Secure VersionpathCookie Path null null -1 null false 0

Note: Only “pathCookie” is available because that is the only cookie whose path is set to "/scwcd/cookie/".

SCWCD Material©2007 IBM Corporation

Page 39: SCWCD 1.4 Material

SCWCD Material 39

Following is the output displayed by “” in new browser session

cookie pos-aged="Positive Aged" ,

Cookies

Name Value Comment Domain Max Age Path Secure Versionpos-aged "Positive Aged" null null -1 null false 0

Note: Only one cookie is displayed, because it is the only cookie with positive non-zero maxAge value.

Also remember when browser sends cookies to server it only sends name-value pairs nothing else.

SCWCD Material©2007 IBM Corporation

Page 40: SCWCD 1.4 Material

SCWCD Material 40

Session

HTTP being “request-response based” (seamless) protocol, session (conversion) across multiple request-response has to be maintained explicitly.

For distributed web applications container makes sure that all requests belonging to one session are handled by single JVM at a given time. If the session is getting migrating from one JVM to other the attributes will also get migrated in container specific ways. If the container cannot support attributes for migration it will throw IllegalArgumentException. To be on safe side all session attributes should implement Serializable interface.

Session (javax.servlet.http.HttpServletRequest) is an object that persists between multiple request-responses between a single user and server.

Session Maintenance

The most common ways of maintaining session is as follows:

Using Cookies Using URL Rewriting Using Secure Socket Layer (SSL) information.

Session maintenance is a two-way job. Both server and client have to co-ordinate. Until the client joins the session, there is no way server can maintain session across multiple requests. A client is said to join a session if session tracking information has been returned to the server indicating that a session has been established in every request.

Using Cookies

When session is maintained using cookies, servlet container creates a unique session ID and typically sends it back to the browser as a cookie. Each subsequent request from this user (at the same browser) passes the cookie containing the session ID, and the servlet container uses this ID to find the user's existing HttpSession object.

The name of the cookie used to track session ID should be “JSESSIONID” (uppercase).

Using URL Rewritting

When the client doesnot support cookies then URL rewritting is used. In this method an addition string is appended to every URL to track session-ID (note it is not parameter nor its part of query sting, in example belw “?” itself is not preent). Generally “jsessionid” (lowecase) string is used to track. But the way URL is updated is container specific.

SCWCD Material©2007 IBM Corporation

Page 41: SCWCD 1.4 Material

SCWCD Material 41

Eg., http://www.myserver.com/catalog/index.html;jsessionid=1234

In order to encode URL with session-ID in all the situations (when needed and skip when not needed) J2EE API provides following two methods in HttpServletRequest. These methods are expected to be used in JSP and servlets when specifying URLs.

String ecodeURL(String url)String encodeRedirectURL(String url)

Both the above methods will check if URL encoding (appending Session-ID) is needed and returns the updated URL (if not updated, same is returned), but different logics are used to check need of URL-encoding as they differ in usage.

encodeRedirectURL() is used only to encode URLs used in sendRedirect() (only local URLs i.e., local to container will get updated otherwise left unaltered).

encodeURL() should be used to encode all the URL that are used/emerged by/from the servlets.

Using SSL information

Secure Sockets Layer, the encryption technology used in the HTTPS protocol, has a built-in mechanism allowing multiple requests from a client to be unambiguously identified as being part of a session. A servlet container can easily use this data to define a session.

Session Timeout

Session timeout is the time after which if there is no interaction from the user, that session will become invalidated. The session timeout can be specified/configured in following ways:

Generally the container (console) will provide a means to specify session-timeout for all the applications running inside it. (Container dependent).

A session timeout can be configured for a web-application using web.xml. This value will be minutes.

<web-app><session-config>

<session-timeout>30</session-timeout> <!-- 30 minutes --></session-config>

</web-app>

SCWCD Material©2007 IBM Corporation

Page 42: SCWCD 1.4 Material

SCWCD Material 42

Programmatically a session-timeout can be accessed/modified using following methods:

int getMaxInactiveInterval() void setMaxInactiveInterval(int time)

Here the time is specified in seconds.

And using the session object, we can programmatically get when the last using interaction (in this session) taken place using following method

long getLastAccessedTime()

This method returns time in mill-seconds since midnight January 1, 1970 GMT.

Similarly session creation time can be accessed using method

long getCreationTime()

This method also returns time in mill-seconds since midnight January 1, 1970 GMT.

NOTE: Once the session is timed out (invalidated) isNew() and getAttribute() will throw IllegalStateException.

Attributes

Attributes are the means by which we can maintain the beans/data/information across the session. Class HttpSession provides following methods for the same:

Object getAttribute(String name)Enumeration getAttributeNames()void setAttribute(String name,Object value)void removeAttribute(String name)

Attributes can be self-notified about session events using following listener interfaces.

Session activation and Passivation Events

SCWCD Material©2007 IBM Corporation

Page 43: SCWCD 1.4 Material

SCWCD Material 43

Container that migrates session between VMs or persists session will notify all its attributes implementing HttpSessionActivationListener about activation/passivation of session using following methods

void sessionDidActivate(HttpSessionEvent e)Notification saying session just got activated.

void sessionWillPassivate(HttpSessionEvent e)Notification saying session is about to get passivated.

HttpSessionEvent contains following methods:

HttpSession getSession()

This listener needs to be configured in Deployment Descriptor to get notified.

Attribute Binding & Unbinding Events

Attributes implementing HttpSessionBindingListener will be notified about when the attribute is getting bound or unbound from the session object. The unbound event can be due to programmer explicitly removing attribute or because session is getting invalidated or timed-out.

void valueBound(HttpSessionBidingEvent e)void valueUnbound(HttpSessionBindingEvent e)

Binding event will be notified once the attribute value is available in the session and unbound event will be notified, once the attribute is removed from the session. Hence, the bound event of new attribute will be called before unbound event of old attribute.

HttpSessionBindingEvent (which extends HttpSessionEvent) have following methods:String getName() //returns attribute name getting bound/unboundObject getValue() //returns attribute value getting bound/unboundHttpSession getSession()

class ActivationBean implements HttpSessionActivationListener{

private String name;public ActivationBean(String name){

this.name=name;}

SCWCD Material©2007 IBM Corporation

Page 44: SCWCD 1.4 Material

SCWCD Material 44

public void sessionWillPassivate(HttpSessionEvent arg0){

System.out.println("Session is getting passivated: "+name);}

public void sessionDidActivate(HttpSessionEvent arg0){

System.out.println("Session is getting activated: "+name);}

}

class BindingBean implements HttpSessionBindingListener{

public void valueBound(HttpSessionBindingEvent e){

System.out.println("Attribute is getting bound: "+e.getName());}

public void valueUnbound(HttpSessionBindingEvent e){

System.out.println("Atribute is getting unbound: "+e.getName());}

}

SCWCD Material©2007 IBM Corporation

Page 45: SCWCD 1.4 Material

SCWCD Material 45

Servlet Code

HttpSession session=req.getSession();

System.out.println("Adding attributes.....");session.setAttribute("binding1",new BindingBean());session.setAttribute("binding2",new BindingBean());session.setAttribute("binding1",new BindingBean());//replacing previous bean

session.setAttribute("activation1",new ActivationBean("activation1"));session.setAttribute("activation2",new ActivationBean("activation2"));

System.out.println("Removing binding attributes....");session.removeAttribute("binding1");session.removeAttribute("binding2");

Output

Attribute is getting bound: binding1Attribute is getting bound: binding2Attribute is getting bound: binding1Attribute is getting unbound: binding1Removing binding attributes....Atribute is getting unbound: binding1Atribute is getting unbound: binding2

And when the server is stopped

Session is getting passivated: activation1Session is getting passivated: activation2

NOTE: For HttpSessionActivationListener there is no need of configuration in web.xml. BUT AS PER SPECIFICATIONS AND BOOKS CONFIGURATION IN WEB.XML IS MANDATORY. So in exams make sure to go according to specification.

SCWCD Material©2007 IBM Corporation

Page 46: SCWCD 1.4 Material

SCWCD Material 46

Request Dispatcher

“Request Dispatcher” (javax.servlet.RequestDispatcher interface) is responsible for forwarding the request (received from client) to the specified resource (servlet, JSP, HTML etc). Application container creates this object and the same can be obtained by following methods of javax.servlet.ServletContext (Note, context represents the application):

RequestDispatcher getRequestDispatcher(String path)o Path should start with “/” and it is intercepted as the root of the

current context. If the other context (application) needs to referred then the context object for that application should be obtained using getContext() method.

RequestDispatcher getNamedDispatcher(String name)o In this method instead of specifying the path, we specify the name

of the resource, which is specifed in web.xml. Note, servlets and JSP can be assigned names in web.xml.

Or the same can be obtained from javax.servlet.ServletRequest using method

RequestDispatcher getRequestDispatcher(String path)o This method is similar to the getRequestDiapatcher() of

ServletContext. With the only difference that, the path can be relative to the current request path (doesn’t start with “/”).

RequestDispatcher have following methods to forward or include other resource.

void forward(ServletRequest req, ServletResponse res) throws IOException,ServletException

o Method forward() should be called before committing response, otherwise IllegalStateException will be thrown. Uncommitted output will get truncated automatically.

void include(ServletRequest req, ServletResponse res) throws IOException,ServletException

o Response path elements and attributes will be kept unchanged.o Target resource cannot change status code or headers. Any such

attempts will be ignored.

SCWCD Material©2007 IBM Corporation

Page 47: SCWCD 1.4 Material

SCWCD Material 47

Note, the request & response parameters to forward()/include() should be same or should be instance of ServletRequestWrapper & ServletResponseWrapper wrapped around these objects.

Query String

The getRequestDispatcher() of both servlet context and request allows to specify optional query string. These parameter values takes precedence over the same named parameters in the request of the including servlet.

String path = "/raisins.jsp?orderno=5";RequestDispatcher rd = context.getRequestDispatcher(path);

Example:Assume there are two servlet - /rd/mainServlet & /rd/subServlet

Main servlet includes/forwards to Subservlet

SCWCD Material©2007 IBM Corporation

Page 48: SCWCD 1.4 Material

SCWCD Material 48

Main Servlet Code

ServletContext context=getServletContext();PrintWriter out=res.getWriter();String action=req.getParameter("action");boolean qryString="true".equals(req.getParameter("qry"));

out.println("This mssg is from main servlet...<BR>");out.println("Request parameters in the main servlet....<BR><BR><BR>");printRequestMap(req.getParameterMap(),out);

out.println("<BR><BR><BR>Request Attributes in the main servlet....<BR><BR><BR>");printAttributes(req.getAttributeNames(),out,req);

out.println("<BR><BR><BR>");

RequestDispatcher rd=null;if(qryString)

rd=context.getRequestDispatcher("/rd/subServlet/test1?value=20");//using contextelse

rd=context.getRequestDispatcher("/rd/subServlet/test2");//using context

if("include".equals(action))rd.include(req,res);

elserd.forward(req,res);

out.println("<BR><BR><BR><B>This mssg is from main servlet after include/forward...</B><BR>");

out.println("<BR><BR><BR>Request Attributes in the main servlet....<BR><BR><BR>");printAttributes(req.getAttributeNames(),out,req);

Sub Servlet Code

PrintWriter out=res.getWriter();

out.println("This mssg is from sub servlet...");Map nameToValue=req.getParameterMap();

out.println("<BR><BR><BR>Request parameters in the sub servlet....<BR><BR><BR>");printRequestMap(nameToValue,out);

out.println("Request Attributes in the sub servlet....<BR><BR><BR>");printAttributes(req.getAttributeNames(),out,req);

SCWCD Material©2007 IBM Corporation

Page 49: SCWCD 1.4 Material

SCWCD Material 49

URLS used for testing:http://localhost:8080/scwcd/rd/mainServlet?action=include&qry=true&value=10http://localhost:8080/scwcd/rd/mainServlet?action=include&qry=falsehttp://localhost:8080/scwcd/rd/mainServlet?action=forward&qry=false&value=10http://localhost:8080/scwcd/rd/mainServlet?action=forward&qry=true&value=10http://localhost:8080/scwcd/rd/mainServlet

Full Source Code:

Automatic Attributes

During forwarding/including resource using request dispatcher there are two resources involved whose properties needs to be accessible to the included/forwarded resource. For this purpose container adds few automatic request attributes that can serve the values of the missing resource properties.

But this (addition of automatic request attributes) happens only when resource is included/forwarded using normal request dispatcher (not named dispatcher). With named dispatcher this will not be the case (because these properties will not be applicable).

Remember when named dispatcher is used: We can not specify query string, because we are suppose to mention servlet

name not path. Since we are mentioning name there is no new URI or paths.

Including ResourceWhen a resource is including following properties of the request will not change even though the current destination is different (this might be needed because once the destination resource is included the control comes back to including servlet).

So container adds request-attributes to reflect these properties according to the included resource.

Information from Included Servlet (Sub-Servlet)Property Attribute & Value Method & Value

Request URI javax.servlet.include.request_uri

/cust/rd/subServlet/test1

getRequestURI()

/cust/rd/mainServlet

SCWCD Material©2007 IBM Corporation

Page 50: SCWCD 1.4 Material

SCWCD Material 50

Context Path javax.servlet.include.context_path

/cust

getContextPath()

/custServlet Path javax.servlet.include.servlet_path

/rd/subServlet

getServletPath()

/rd/mainServletPath Info javax.servlet.include.path_info

/test1

getPathInfo()

nullQuery String javax.servlet.include.query_string

value=20

getQueryString()

action=include&qry=true&value=10

Forwarding requestWhen a request is forwarded to other resource following properties of request will change (this might be needed because the forwarding servlet will not participate in serving the request).

So container adds request attributes to reflect these properties according to forwarding resource.

Information from forwarded Servlet (Sub-Servlet)Property Attribute & Value Method & Value

Request URI javax.servlet.forward.request_uri

/cust/rd/mainServlet

getRequestURI()

/cust/rd/subServlet/test1Context Path javax.servlet.forward.context_path

/cust

getContextPath()

/custServlet Path javax.servlet.forward.servlet_path

/rd/mainServlet

getServletPath()

/rd/subServletPath Info javax.servlet.forward.path_info

null (actually no attribute)

getPathInfo()

/test1Query String javax.servlet.forward.query_string

value=20

getQueryString()

value=20

Note: Among above mentioned attributes path_info & query_string values may not be present in the cases where these values result in null.

Due to some exception when the request is forwarded to an error JSP page/resource following automatic request-attributes will be set by the container

SCWCD Material©2007 IBM Corporation

Page 51: SCWCD 1.4 Material

SCWCD Material 51

Attribute Name Typejavax.servlet.error.status_code java.lang.Integerjavax.servlet.error.exception_type java.lang.Classjavax.servlet.error.message java.lang.Stringjavax.servlet.error.exception java.lang.Throwablejavax.servlet.error.request_uri java.lang.Stringjavax.servlet.error.servlet_name java.lang.String

This information will help error pages to generate specialized content.

SCWCD Material©2007 IBM Corporation

Page 52: SCWCD 1.4 Material

SCWCD Material 52

Attributes

Attribute is the means by which information/data/beans can be transferred among multiple resources (servlets, JSPs) and the container.

Scopes

Attributes can be maintained in different scopes depending on the requirement and circumstances. Following table illustrates the scenarios where different scopes can be used:

Scope (class) DescriptionRequest(javax.servlet.ServletRequest)

When the attributes needs to be available across multiple servlets/pages when serving single request.

Session(javax.servlet.http.HttpSession)

When the attributes needs to be available across multiple servlets/pages across multiple requests of single session.

Application(javax.servlet.ServletContext)

When the attributes needs to be commonly available across all sessions.

In order to maintain attributes in these scopes all the three classes provides following set of 4 methods:

void setAttribute(String name, Object value)Sets the attribute with the specified name and value.

Object getAttribute(String name)Returns the value associated with the specified attribute name.

Enumeration getAttributeNames()Returns an enumeration of attribute names.

void removeAttribute(String name)Removes the attribute corresponding to specified name.

Important points regarding the attributes:1. Attributes in request and context scopes may be used (by automatically

attributes) by container to convey information to the resources. For example, requests made using HTTPS, the attribute javax.servlet.request.X509Certificate can be used to retrieve information on the certificate of the client.

2. As per java specifications, the attribute names in request and context scope should follow same conventions as package names (Eg., com.example.request). Names like java.*, javax.* and sun.* are reserved by sun specifications.

Note: Session scope (javax.servlet.http.ServletContext) does not specify any thing about attribute naming conventions.

SCWCD Material©2007 IBM Corporation

Page 53: SCWCD 1.4 Material

SCWCD Material 53

3. As session (due to long time-out or in distributed applications) may get passivated/activated, it is always preferred to have session scope attribute values as serializable. The activation/passivation may also be the result of moving session object from one JVM to other in distributed applications.

Attributes & Multi-threading

Context (application) Scope: These scoped attributes are not thread safe. Different servlets provide service to different users simultaneously in multiple threads. And all the servlets can access (add/replace/remove attributes) the ServletContext object at same time. So in order to be on safe side servlet code should synchronize on ServletContext object before accessing context attributes.

synchronized(context){

context.setAttribute(“key”,”value”);}

Session Scope: These scoped attributes are not thread safe. Even though session belongs to single user there might be multiple threads running to serve the same client (in same session). For example, user might open multiple windows and even in the case of applications following “Composite View Pattern” browser may decide to make multiple request simultaneously to display “Composite View page”. So in order to access attributes in session we need to synchronize on “session” object.

synchronized(session){

sesion.setAttribute(“key”,”value”);}

Request Scope: These attributes are thread safe. For every request made by the user anew request object is built and is served in a new thread. This request object should not be accessed in other threads. Hence request scoped attributes are thread-safe.

Attributes & Distributed Applications

An application can be marked as distributable (in its deployment descriptor) and in that case application will run on container that runs on multiple JVMs. For such applications each JVM will have its own instance of ServletContext. And depending on the load container may decide to shift session from one JVM to other.

Note: The activation & passivation of session may also take place due to long session timeouts.

SCWCD Material©2007 IBM Corporation

Page 54: SCWCD 1.4 Material

SCWCD Material 54

So following restrictions will be applied on attributes for distribute applications:1. Since session may get passivated and activated or get shifted from one JVM to

other, it is always preferred to have session scope attribute values as serializable. J2EE server may not use standard serialization/deserialization mechanisms so writeObject() and readObject() of session attributes may not get called even during activation/passivation process even though they implement Serializable interface.

2. The attributes in context scope will not be transferred across multiple JVMs. Hence, context scope attributes should not be used in distributed applications for sharing information/data between resources (instead some common cache/database should be used to maintain application level information).

SCWCD Material©2007 IBM Corporation

Page 55: SCWCD 1.4 Material

SCWCD Material 55

Listeners

We can configure listeners to receive notification regarding addition, removal and replacement of attributes in different scopes – request, session & application. And we can also receive notifications about the life cycle of the different scopes. Following table describes the ways to configure for the same.

Attribute Listeners Life Cycle ListenersRequest javax.servlet.ServletRequestAttributeListener

attributeAdded(ServletRequestAttributeEvent e)attributeRemoved(ServletRequestAttributeEvent e)attributeReplaced(ServletRequestAttributeEvent e)

javax.servlet.ServletRequestListener

requestInitalized(ServletRequestEvent e)requestDestroyed(ServletRequestEvent e)

Session javax.servlet.http.HttpSessionAttributeListener

attributeAdded(HttpSessionBindingEvent e)attributeRemoved(HttpSessionBindingEvent e)attributeReplaced(HttpSessionBindingEvent e)

Note: Here event type is HttpSessionBindingEvent

javax.servlet.http.HttpSessionListener

sessionCreated(HttpSessionEvent e)sessionDestroyed(HttpSessionEvent e)

Note: Here method name is sessionCreated() not sessionInitalized()

Application (Context)

javax.servlet.ServletContextAttributeListener

attributeAdded(ServletContextAttributeEvent e)attributeRemoved(ServletContextAttributeEvent e)attributeReplaced(ServletContextAttributeEvent e)

javax.servlet.ServletContextListener

contextInitalized(ServletContextEvent e)contextDestroyed(SevletContextEvent e)

Following table illustrates the services offered by different event objects accessible in event methods of above listeners

Event Class Name ServicesServletRequestAttributeEvent Extends ServletRequestEvent

String getName()Object getValue()

ServletRequestEvent ServletContext getServletContext()ServletRequest getServletRequest()

SCWCD Material©2007 IBM Corporation

Page 56: SCWCD 1.4 Material

SCWCD Material 56

HttpSessionBindingEvent Extends HttpSessionEvent

String getName()Object getValue()HttpSession getSession()

HttpSessionEvent HttpSession getSession()

ServletContextAttributeEvent Extends ServletContextEvent

String getName()Object getValue()

SevletContextEvent ServletContext getServletContext()

Note: Remember all attribute events (eg ServletRequestAttributeEvent) extends from normal listener events (eg ServletRequestEvent).

<web-app version="2.4">………………….

<listener><listener-class>com.test.list.ContextAttList</listener-class>

</listener><listener>

<listener-class>com.test.list.ContextList</listener-class></listener>

<listener><listener-class>com.test.list.SessionList</listener-class>

</listener></web-app>

Generally listeners (attributes addition/removal or life cycle starting) will be invoked in the order they are configured in web.xml. But the end of the life-cycle of any scope (session, request and context) will be notified to the listeners in reverse order.

web.xml configuration

SCWCD Material©2007 IBM Corporation

Page 57: SCWCD 1.4 Material

SCWCD Material 57

<listener><listener-class>com.test.list.ServReqList</listener-class>

</listener>

<listener><listener-class>com.test.list.ServReqList2</listener-class>

</listener>

First Listener Class

public class ServReqList implements ServletRequestListener{

public void requestDestroyed(ServletRequestEvent e){

System.out.println("Class: ServReqList Method: requestDestroyed");}

public void requestInitialized(ServletRequestEvent e){

System.out.println("Class: ServReqList Method: requestInitialized");}

}

Second Listener Class

public class ServReqList2 implements ServletRequestListener{

public void requestDestroyed(ServletRequestEvent e){

System.out.println("Class: ServReqList2 Method: requestDestroyed");}

public void requestInitialized(ServletRequestEvent e){

System.out.println("Class: ServReqList2 Method: requestInitialized");}

}

Output

Class: ServReqList Method: requestInitializedClass: ServReqList2 Method: requestInitialized

SCWCD Material©2007 IBM Corporation

Page 58: SCWCD 1.4 Material

SCWCD Material 58

Class: ServReqList Method: requestDestroyedClass: ServReqList2 Method: requestDestroyed

NOTE: In attribute listeners when an attribute is set to null value, then it is equivalent to calling removeAttribute() so attributeRemoved() method will get invoked.

Special Session Related Listeners

As session attributes generally plays important roles in application, special listeners are provided for session attributes.

HttpSessionActivationListener: Since session may migrate from one VM to other (in distribute applications) and may persist for long time (using caching mechanism) J2EE provides this listener to notify session attribute values implementing this interface when session is getting activated/passivated using following event methods.

void sessionDidActivate(SessionEvent e)void sessionWillPassivate(SessionEvent e)

HttpSessionBidingListener: Session attributes implementing this interface will be notified when they are bound/unbound to session using following event methods:

void valueBound(HttpSessionBindingEvent e)void valueUnbound(HttpSessionBindingEvent e)

HttpSessionBidingListener and HttpSessionActivationListener should not be configured in deployment descriptor and will be notified automatically if the instance of these interface implementations are part of session attributes.

NOTE: For HttpSessionActivationListener there is no need of configuration in web.xml. BUT AS PER SPECIFICATIONS AND BOOKS CONFIGURATION IN WEB.XML IS MANDATORY. So in exams make sure to go according to specification.

Filters

SCWCD Material©2007 IBM Corporation

Page 59: SCWCD 1.4 Material

Init

doFilter

Destroy

SCWCD Material 59

A web application filter is meant for filtering request/response sent from client/server to server/client. Following diagram illustrates the same:

Depending on the configured URL pattern in web.xml a filter will be chosen to filter request and responses to the resource.

Multiple filters can be configured for the same resource. The order of configuring filters in web.xml will be used to invoke filters in the same order for any given resource.

Filters mapped by <url-pattern> will be invoked before filters mapped by <servlet-name>.

A filter is a class, which implements javax.servlet.Filter interface directly or indirectly.

Filter Life Cycle

Just like servlet filter is also having three methods. Following is the description of the 3 steps of servlet life cycle.

1. Initialization : The filter is initialized by calling init() method of filter. The call to this method indicates the filter is going to be placed for service. And this method is called only once (unless init() method is unsuccessful) and expected to initialize the resources needed by the filter.

If this method (init()) throws SevletException or doesn’t return in time defined by web server, then the filter will not used for filtering job

void init(FilterConfig config)

2. Filter : Container calls the doFilter() method each time a request/response pair is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain instance passed in to this method allows the Filter to pass on the request and response to the next entity in the chain.

This method might be called in multiple threads to serve multiple requests simultaneously; so shared resource access should be synchronized properly.

A typical Filtering job will follow following pattern: Analyze the request

SCWCD Material©2007 IBM Corporation

Page 60: SCWCD 1.4 Material

SCWCD Material 60

Optionally wrap the request/response objects in wrappers (ServletRequestWrapper/ServletResponseWrapper or HttpServletRequestWrapper/HttpServletResponseWrapper) to filter headers/content in later stages.

Either pass the request/response to next entity in the chain (FilterChain.doFilter()) or process the request and send response by itself (without continuing the chain).

Manipulate the final response object (if wrapper was used).

void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)

3. Destroy : “Servlet Container” will call destroy() method of the filter to indicate, that the filter is being removed out of service. After this method call, doFilter() method will not be called on this filter.

This method is expected to release/cleanup the resources this filter is holding. Before the servlet container calls the destroy method, it will allow any threads that are currently running in the doFilter() method of the filter to complete execution, or exceed a server-defined time limit. After the destroy method completes, the servlet container will release the filter instance so that it is eligible for garbage collection.

void destroy()

Note: Unlike Servlet interface, Filter interface does not contain any additional methods other than its life cycle methods.

NOTE: All filter life cycle methods are container call-back methods. But doFilter() is both call-back method and also inline method.

FilterConfig

An instance of FilterConfig will be passed by the container to the init() method of the filter during initialization. And this instance represents the configuration information of the file as specified in web.xml. Following methods of this interface can be used to fetch the configuration information:

Init Parameters: Init parameters as configured in web.xml can be accessed using following methods

o String getInitParameter(String name) Returns the value of the specified init parameter.

o Enumeration getInitParameterNames() Returns the enumeration of the init parameters

SCWCD Material©2007 IBM Corporation

Page 61: SCWCD 1.4 Material

SCWCD Material 61

Filter Name: The name of the filter as configured in web.xml.o String getFilterName()

Servlet Context: An instance of the servlet context can be obtained using following method

o ServletContext getServletContext()

FilterChain

This interface represents the chain of filters and final resource to be invoked. The instance of this interface will be passes by container to doFilter() of the filter, so that filter can handle the job of filtering or serving the request by next resource.

FilterChain consists of only one method as described below: void doFilter(ServletRequest req, ServletResponse res)

o This method allows filter to transfer the request or response (or their wrappers) to next filter or the destination resource.

Wrapper Classes

Filter may wrap the actual request/response in wrapper class extensions.javax.servlet.ServletRequestWrapper & javax.servlet.ServletResponseWrapperjavax.servlet.http.HttpServletRequestWrapper &

javax.servlet.http.HttpServletResponseWrapper

Generally, custom wrapper classes will be coded to extend one of the above classes and override certain methods for customization and store data in customized format and finally after the response is received in back-path the data is manipulated accordingly and will be sent back to the client.

Applications of Filters

Authentication Filters Logging and Auditing Filters Image conversion Filters Data compression Filters Encryption Filters Tokenizing Filters Filters that trigger resource access events XSL/T filters Mime-type chain Filter

SCWCD Material©2007 IBM Corporation

Page 62: SCWCD 1.4 Material

SCWCD Material 62

Example

In this example, we want to filter text files.All the text files should be filtered by TextFileFilter

(replaces “,” with “_______”)Text files from dir1 should be filter by DummyFilter3 & DummyFilter1

(Attaches header and Footer)Text files from dir2 should be filter by DummyFilter2 & DummyFilter3

(Attaches header and Footer)

Since the TextFileFilter has to act on the response object at the end, “Response Wrapper” should be used.

SCWCD Material©2007 IBM Corporation

Page 63: SCWCD 1.4 Material

SCWCD Material 63

WEB.XML Filter Configuration

<filter><filter-name>TextFileFilter</filter-name><filter-class>com.test.filter.TextFileFilter</filter-class>

</filter><filter>

<filter-name>DummyFilter1</filter-name><filter-class>com.test.filter.DummyFilter1</filter-class>

</filter>

... ... ...

<filter-mapping><filter-name>TextFileFilter</filter-name><url-pattern>*.txt</url-pattern>

</filter-mapping><filter-mapping>

<filter-name>DummyFilter3</filter-name><url-pattern>/dir1/*</url-pattern>

</filter-mapping><filter-mapping>

<filter-name>DummyFilter1</filter-name><url-pattern>/dir1/*</url-pattern>

</filter-mapping><filter-mapping>

<filter-name>DummyFilter2</filter-name><url-pattern>/dir2/*</url-pattern>

</filter-mapping><filter-mapping>

<filter-name>DummyFilter3</filter-name><url-pattern>/dir2/*</url-pattern>

</filter-mapping>

Notes:For “dir1/*” the order of <filter-mapping> nodes determines filter-chain as DummyFilter3 then DummyFilter1.

Similarly, For “dir2/*” the order of <filter-mapping> nodes determines filter-chain as DummyFilter2 then DummyFilter3.

SCWCD Material©2007 IBM Corporation

Page 64: SCWCD 1.4 Material

SCWCD Material 64

TextFileFilter

class TFOutputStream extends ServletOutputStream{

private ByteArrayOutputStream bos=new ByteArrayOutputStream();public void write(int val) throws IOException{

bos.write(val);}

public byte[] getBytes(){

return bos.toByteArray();}

}

//A Response wrapper with custom output streamclass TFResponseWrapper extends HttpServletResponseWrapper{

private PrintWriter out=null;private TFOutputStream os=null;HttpServletResponse res=null;

public TFResponseWrapper(HttpServletResponse res){

super(res);os=new TFOutputStream();out=new PrintWriter(os);this.res=res;

}public ServletOutputStream getOutputStream() throws IOException{

return os;}

public PrintWriter getWriter() throws IOException{

return out;}

public String getData() throws IOException{

out.flush();os.flush();return new String(os.getBytes());

}

SCWCD Material©2007 IBM Corporation

Page 65: SCWCD 1.4 Material

SCWCD Material 65

public void setData(String data) throws IOException{

super.getResponse().getWriter().append(data);super.getResponse().getWriter().flush();

}

}

public class TextFileFilter implements Filter{

public void init(FilterConfig config) throws ServletException{}

public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException

{HttpServletRequest httpReq=(HttpServletRequest)req;HttpServletResponse httpRes=(HttpServletResponse)res;TFResponseWrapper tfRes=new TFResponseWrapper(httpRes);

chain.doFilter(req,tfRes);

String data=tfRes.getData();tfRes.setData(data.replaceAll(",","________"));

}

public void destroy(){}

}

Filter & Request Dispatcher

Even though there is a URL pattern match, normally a filter will not be invoked when a resource is invoked/used using RequestDispatcher.include() or RequestDispatcher.forward() methods. In the same way a filter will not be invoked even when the resource is invoked as part of error mechanism (due to some exception).

This behavior can be changed by using <dispatcher> element of <filter-mapping> element in web.xml. This element can hold one of the following values:

SCWCD Material©2007 IBM Corporation

Page 66: SCWCD 1.4 Material

SCWCD Material 66

Dispatcher Type

Description

REQUEST Invoke the filter only when request comes directly from client.FORWARD When the resource is invoked using RequestDisptcher.forward()INCLUDE When the resource is invoked using RequestDisptcher.include()ERROR When the resource is being invoked as part of error handling mechanism.

SCWCD Material©2007 IBM Corporation

Page 67: SCWCD 1.4 Material

SCWCD Material 67

JSP

JSP is a tagged version of servlets. Life cycle of JSP pages consists of following two phases:

Translation Phase: Container will validate the JSP code and translates JSP into a java class, a servlet class. Note, every valid JSP will have an equivalent XML document version.

Execution Phase: In this phase container will take care of creating one/multiple instances (or use multi-threading) of this servlet class and serve client requests.

Conversion of JSP into servlet class is container-specific.

JspPage Interface & Event Methods

Even though JSP handles HTTP protocol, it is not limited to HTTTP. The container can convert JSP to serve any protocol. All JSP converted classes will implement javax.servlet.jsp.JspPage interface directly or indirectly.

The interface javax.servlet.jsp.JspPage defines a protocol with 3 methods; only two of them: jspInit() and jspDestroy() are part of this interface as the signature of the third method: _jspService() depends on the specific protocol used and cannot be expressed in a generic way in Java.

public void jspInit()o Initialization event method of JSP page. ServletConfig can be accessed

using getServletConfig(). public void jspDestroy()

o Destruction event method of JSP page.

HTTPJspPage & Service method

All the JSP servlet classes, which are meant for HTTP protocol should implement interface javax.servlet.jsp.HttpJspPage, which in turn extends javax.servlet.jsp.JspPage interface. So the additional method, which is HTTP protocol specific, is as follows:

public void _jspService(HttpServletRequest req, HttpServletResponse res)o This method is automatically defined by container and should not be

defined by JSP author.o If a super class is defined for the JSP page, then super class may perform

some action in service method. Note, this method will be overridden by the generated JSP servlet class. Generally, super class should not be specified, because the class being specified should take care of calling _jspService methods, implicit object declaration etc.

SCWCD Material©2007 IBM Corporation

Page 68: SCWCD 1.4 Material

SCWCD Material 68

URL in JSP

In JSP standard actions or tags, JSP supports two types of URLs: Context Relative Path: Path that starts with “/” and is interpreted to be relative to

context root. (That is context root should not be specified). Note, the context root name can be obtained from getContextPath() of ServletRequest object. Note, getContextPath() will return context path starting with “/”.

Page Relative Path: Path that does not start with “/” and is interpreted relative to the JSP file.

Note the URL specification mentioned above will not be applicable for declaring URL outside JSP standard tags like hyper links, form actions etc. They are applicable only for JSP tags like action include (page attribute), directive include (file attribute) etc.

/jsps/test.jsp

<%final String CONTEXT_NAME=request.getContextPath();

%><HTML><body>

This mssg is from JSP main page and request URI is: <%=request.getRequestURI()%>

<BR><jsp:include page="/testSub.jsp"></jsp:include><BR>This is a test <a href="/testSub.jsp">link</a> without context name.

<%-- This link will not work --%><BR>This is a test <a href="<%=CONTEXT_NAME%>/testSub.jsp">link</a> with context

name.<%-- This link will work --%>

</body>

/testSub.jsp

This mssg is from JSP Sub page.

SCWCD Material©2007 IBM Corporation

Page 69: SCWCD 1.4 Material

SCWCD Material 69

Errors & Error Pages

In JSP lifetime error can occur at any time and their result can be described as follows: Translation Phase Errors: When user request for a page and container is unable

to convert the appropriate JSP into servlet class then protocol specific error will be returned. For HTTP, error 500 (server error) will be returned.

Note, even if the jspInit() method throws any exception, error 500 will be returned, indicating page is not available for service.

Request Processing Time Errors: If the JSP body execution results in any uncaught exceptions, then the request will be forwarded to the error page (if specified) by passing information about error as request attributes. If error page is not specified, error 500 will be sent to client (generally with exception stack trace).

Error PageA page can be declared as an error page by specifying isErrorPage=”true” attribute in “page” directive.

In an error page, implicit variable exception will be initialized. And the value of “exception” will be set to the value of request attribute “javax.servlet.error.exception” if present, otherwise it will be set to “javax.servlet.jsp.jspException” attribute value.

<%@page isErrorPage="true" import="java.io.*"%><HTML><body>

Exception occurred is: <%=exception%><BR>Attribute javax.servlet.error.exception value is: <

%=request.getAttribute("javax.servlet.error.exception")%><BR>Attribute javax.servlet.jsp.jspException value is: <

%=request.getAttribute("javax.servlet.jsp.jspException")%><BR><BR><BR><BR><BR><BR><BR><BR><%

exception.printStackTrace(new PrintWriter(out));%>

</body></HTML>

SCWCD Material©2007 IBM Corporation

Page 70: SCWCD 1.4 Material

SCWCD Material 70

In addition, an ErrorData instance must be initialized based on the error handler ServletRequest attributes defined by the Servlet specification, and made available through the PageContext to the page.

Note: Attribute “javax.servlet.jsp.jspException” is used for backward compatibility.

An error page can be used as normal page. The only difference comes is that in an error page which is used as normal page, implicit variable exception will be null. Whereas in normal pages there will be no implicit variable exception.

Implicit Imports & Objects

JSP will include following import statements by default

import javax.servlet.*;import javax.servlet.http.*;import javax.servlet.jsp.*;

Some of objects are directly available to JSP page (without declaration) and are implicit objects. And objects exposed as scripting variable has a scope within page. Following is the list of implicit objects and their descriptions available to JSP.

Object names with prefixes jsp, _jsp, jspx and _jspx, in any combination of upper and lower case, are reserved by the JSP specification.

Implicit Object Name

Description

request Type: Depending on protocol it can be javax.servlet.ServletRequest or its subclass (Eg, javax.servlet.http.HttpServletRequest)

Represents the request object. Can be used to access request scope attributes.response Type: Depending on protocol it can be javax.servlet.ServletResponse or its

subclass (Eg, javax.servlet.http.HttpServletResponse)

Represents response object of the page.pageContext Type: javax.servlet.jsp.PageContext

Page context for this page and can be used to access page scope attributes.session Type: javax.servlet.http.HttpSession

This variable is valid only for HTTP protocol.

Available only in session aware pages.

SCWCD Material©2007 IBM Corporation

Page 71: SCWCD 1.4 Material

SCWCD Material 71

Represents current user session. Can be used to access session scope attributes.

application Type: javax.servlet.ServletContext

Current application context and used to access application scope attributes.out Type: javax.servlet.jsp.JspWriter

Represents response output stream.config Type: javax.servlet.ServletConfig

ServletConfig of the current page.Page Type: java.lang.Object

Instance of this page implementation class.exception Type: java.lang.Throwable

This implicit object is available only in error pages (isErrorPage=”true” in page directive).

Throwable object (exception occurred in main page) that resulted in the invocation of this error page.

Note: Implicit objects are not available to event methods or any methods declared using declarations.

A JSP translated page looks like follows:

SCWCD Material©2007 IBM Corporation

Page 72: SCWCD 1.4 Material

SCWCD Material 72

public final class test_jsp extends org.apache.jasper.runtime.HttpJspBase implements org.apache.jasper.runtime.JspSourceDependent {public void jspInit(){

...........}public void jspDestroy(){

........}

public void _jspService(HttpServletRequest request, HttpServletResponse response)

throws java.io.IOException, ServletException {

JspFactory _jspxFactory = null;PageContext pageContext = null;HttpSession session = null;ServletContext application = null;ServletConfig config = null;JspWriter out = null;Object page = this;JspWriter _jspx_out = null;PageContext _jspx_page_context = null;...............................

}}

Attributes & Scopes

Objects in JSP in created in multiple ways – implicit objects, objects created by scripting elements and some created by action elements. In all cases all objects are associated with a scope and can be accessed as attributes in that scope. Following is the list of scopes and their descriptions:

Scope DescriptionPage Accessible within the page where they are created.

Deleted once the response is sent or request is forwarded to other resource.

SCWCD Material©2007 IBM Corporation

Page 73: SCWCD 1.4 Material

SCWCD Material 73

Stored in pageContext.Request Accessible to all the resources serving this request.

Useful during forwarding/including request to other resource.Session Available across the current session.Application Available across the application.

Stored in application object. (ServletContext).

As per the standards, a name should refer to a unique object at all points in the execution; that is, all the different scopes really should behave as a single name space. A JSP container implementation may or may not enforce this rule explicitly for performance reasons.

SCWCD Material©2007 IBM Corporation

Page 74: SCWCD 1.4 Material

SCWCD Material 74

JSP Elements

In JSP there are three types of elements:1. Directives: Provides information which is used for JSP translation and

conceptually independent of request (unless JSP logic enforces with conditions which in turn are based on request).

Syntax: <%@ directive & attributes %>

2. Actions: Provides information in request processing phase and generally depends on request. There are two types of actions – standard, custom. Actions syntax follows XML syntax (start tag, attributes, optional body and end tag).

Syntax: <tag-name attributes…>Body

</tag-name>3. Scripting Elements: Scripting element provides ways to access/use the specified

scripting language (currently only java). Scripting element can be sub-divided into following three types:

DeclarationsSyntax: <%! ………… %>

ScriptletsSyntax: <% …………… %>

ExpressionsSyntax: <%= ………… %>

4. Comments: Comments in the JSP page can be mentioned using following syntax. Comments will not be processed or translated by the container. Nested comments are not allowed.

Syntax: <%-- Comment --%>

Alternatively, comments can also be specified in the script elements in the scripting language style.

Syntax: <% /* this is a comment */ %>

Note: <!-- --> is not a JSP comment and it will be processed and will be sent to the client as part of output. These are HTML (XML) comments.

Escape Sequences

In attribute values single quote can be quoted as \’ and double quotes \” Similarly <% as <\% and %> as %\> If EL evaluation is enable then $ can be quotes as \$

SCWCD Material©2007 IBM Corporation

Page 75: SCWCD 1.4 Material

SCWCD Material 75

The entities &apos; and &quot; are available to describe single and double quotes.

Important Rules

Starting and ending tags of a tag should be in the same file. This rules applies for alternate syntaxes also – script elements, actions and directives.

Attribute names starting with jsp, _jsp, java & sun are reserved by sun. The syntaxes can have white spaces in middle but should not alter the syntax. For

example <% can not have white space between < & %.

SCWCD Material©2007 IBM Corporation

Page 76: SCWCD 1.4 Material

SCWCD Material 76

Directives

Directive “page”

The page directive defines a number of page dependent properties and communicates these to the JSP container.

JSP can have more than one page directive and at any position (after translation everything will be clubbed). Page directive specifying pageEncoding and contentType attributes should appear at the beginning of the page. Attribute pageEncoding can occur only once.

If the same attribute is specified multiple times in the page, then the values should be same. Import attribute is the exemption for this rule.

Page DirectiveAttribute Name Description

language Defines scripting language that can be used in scripting elements. Currently only java is available.

extends Specifies the fully specified super class name. Generally this will not be used. If defined, parent class has to take care of calling even methods, declaration of implicit objects and other.

import List of packages/classes delimited by comma (,) that needs to be imported. By default following packages/classes are imported into JSP page:

java.lang.*javax.servlet.*javax.servlet.jsp.* javax.servlet.http.*.

session Values can be true/false. Indicates whether page needs to participate in session. If false, implicit object “session” will not be available.

Default value is true.buffer Specifies buffer size of JspWriter, if “none”, then the contents will

be immediately written response.

The size can be specified only in kilobytes and suffix kb is mandatory. Depending on autoFlush attribute contents of this

SCWCD Material©2007 IBM Corporation

Page 77: SCWCD 1.4 Material

SCWCD Material 77

buffer is either automatically flushed, or an exception is raised, when overflow would occur.

Default value is >= 8kb (container dependent).autoFlush Specifies whether the buffered output should be flushed

automatically (true value) when the buffer is filled, or whether an exception should be raised (false value) to indicate buffer overflow.

It is illegal, resulting in a translation error, to set autoFlush to false when buffer=none.

The default value is true.isThreadSafe Deprecated.

If true, this page can serve multiple users concurrently.info Defines information about this page. Same as getServletInfo() in a

servlet. isErrorPage Declares this page as error page.

Only for error pages implicit object “exception” is available.

Default value is false.errorPage Declares an error page (URL) to be used when an un-handled

exception occurs.

If autoFlush is true, and if any contents are sent to client (response is committed) then request may not be forwarded to error page.

If this value is specified, error page specified in web.xml will not be used.

contentType Specifies the MIME content type of the page. Equivalent to setContentType() of response object.

pageEncoding Specifies the CHARSET (encoding scheme) of the page. Equivalent to setPageEncoding() of response object.

isELIgnored Defines whether EL expressions are ignored or evaluated for this page and translation unit.

Default value varies depending on web.xml version.

Directive “taglib”

SCWCD Material©2007 IBM Corporation

Page 78: SCWCD 1.4 Material

SCWCD Material 78

The taglib directive in a JSP page declares that the page uses a tag library, uniquely identifies the tag library using a URI and associates a tag prefix that will distinguish usage of the actions in the library.

Syntax<%@ taglib ( uri=”tagLibraryURI” | tagdir=”tagDir” ) prefix=”tagPrefix” %>

where the attributes are:

taglib DirectiveAttribute Name Description

uri Either an absolute URI or a relative URI specification that uniquely identifies the tag library descriptor associated with this prefix.

tagdir Indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory.

Error may occur in following cases: Value does not start with /WEB-INF/tags/. Value does not point to a directory that exists. If used in conjunction with the uri attribute.

prefix Defines the prefix string in that is used to distinguish a custom action, e.g <myPrefix:myTag>.

Prefixes starting with jsp:, jspx:, java:, javax:, servlet:, sun:, and sunw: are reserved.

A prefix must follow the naming convention specified in theXML namespaces specification. Empty prefixes are illegal in this version of the specification.

Directive “include”

The include directive is used to substitute text and/or code at JSP page translation-time. The <%@ include file=”relativeURLspec” %> directive inserts the text of the specified resource into the page or tag file. The included file is subject to the access control available to the JSP container.

A JSP container can include a mechanism for being notified if an included file changes, so the container can recompile the JSP page. However, the JSP 2.0 specification does not have a way of directing the JSP container that included files have changed.

Examples<%@ include file=”copyright.html” %>

SCWCD Material©2007 IBM Corporation

Page 79: SCWCD 1.4 Material

SCWCD Material 79

Syntax<%@ include file="relativeURLspec" %>

Difference between directive include and jsp:include

<%@ include file=... %> filerelative

static

Content is parsed by JSP container.

<jsp:include page= /> pagerelative

static and dynamic

Content is not parsed; it is included in place.

SCWCD Material©2007 IBM Corporation

Page 80: SCWCD 1.4 Material

SCWCD Material 80

Scripting Elements

There are three classes of scripting elements: declarations, scriptlets and expressions.

Declarations

Declarations are used to declare class/instance level variables, which are accessible to entire page.

Syntax <%! this is a declaration %>

Examples:<%! int i; %><%! int i = 0; %><%! public String f(int i) { if (i<3) return(“...”); ... } %>

Scriptlets

Scriptlets are used to describe actions to be performed in response to some request. Scriptlets that are program fragments can also be used to do things like iterations and conditional execution of other elements in the JSP page. Scriptlets are executed at request-processing time.

Syntax<% this is a scriptlet %>

Example<%

int i=20;if (value==100)

{%>

Good Morning<%

} else

SCWCD Material©2007 IBM Corporation

Page 81: SCWCD 1.4 Material

SCWCD Material 81

{ %>

Good Afternoon<%

} %>

Expressions

Expressions are complete expressions in the scripting language that get evaluated at response time; commonly, the result is converted into a string and inserted into the output stream.

If the result of the expression cannot be coerced to a String the following must happen: If the problem is detected at translation time, a translation time error shall occur. If the coercion cannot be detected during translation, a ClassCastException shall be raised at request time.

Expressions are evaluated left-to-right in the JSP page. If an expression appears in more than one run-time attribute, they are evaluated left-to-right in the tag.

Syntax<%= this is an expression %>

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

Disabling/Enabling Scripting elements

With the introduction of EL expressions there is very less need for the scripting elements and JSP 2.0 discourages to use scripting elements. So if an application wants to disable scripting elements, it can be configured in web.xml file as follows:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4">

<display-name>Custom Tags</display-name><jsp-config>

<jsp-property-group><url-pattern>*.svg</url-pattern><is-xml>true</is-xml>

</jsp-property-group>

SCWCD Material©2007 IBM Corporation

Page 82: SCWCD 1.4 Material

SCWCD Material 82

<jsp-property-group><url-pattern>*.jsp</url-pattern><scripting-invalid>true</scripting-invalid>

</jsp-property-group></jsp-config>

</web-app>

Standard Actions

An action is just like XML node element and syntax looks like<pre:name attr1=”val1” attr2=”val2”>

body</pre:name>

where pre - Prefixname - Name of the action/tagattr1, attr2 - Attribute namesval1, val2 - Attribute valuesbody - Body of the action. It can be simple text or nested actions.

The interpretation of all actions (both custom and standard) start by evaluating the values given to its attributes left to right, and assigning the values to the attributes.

Runtime Expressions

An attribute of an action can be runtime expression, in which case the attribute value can be specified using expression or using EL expression.

When the scriptlet expression is used the value should be composed of single expression only. That is, multiple expressions or String & expression combination cannot be used. And the value of expression is directly assigned to the attribute method (no automatic conversions will be taken place).

When static text is specified it will be converted into attribute types as per following tables.

When EL expression is used in combination with static text or other EL expression it is converted into String and then conversion is taken place as per below table. When EL expression alone is used by default it behaves like Object just like scriptlet expression, but if conversion needed, it gets converted to string and then appropriate type.

Type Description of ConversionBean Property As converted by the corresponding PropertyEditor, if any, using

SCWCD Material©2007 IBM Corporation

Page 83: SCWCD 1.4 Material

SCWCD Material 83

PropertyEditor.setAsText(string-literal) and PropertyEditor.

getValue(). If there is no corresponding PropertyEditor or the PropertyEditor throws an exception, ‘null’ if the string is empty, otherwise error.

boolean orBoolean

As indicated in Boolean.valueOf(String). This results in ‘false’ if the String is empty.

byte or Byte As indicated in Byte.valueOf(String), or ‘(byte) 0’ if the string is empty.

char or Character

As indicated in String.charAt(0), or ‘(char) 0’ if the string is empty.

double or Double

As indicated in Double.valueOf(String), or 0 if the string is empty.

int or Integer As indicated in Integer.valueOf(String), or 0 if the string is empty.

float or Float As indicated in Float.valueOf(String), or 0 if the string is empty.

long or Long As indicated in Long.valueOf(String), or 0 if the string is empty.

short or Short As indicated in Short.valueOf(String), or 0 if the string is empty.

Object or String

As if new String(string-literal). This results in new String( ““ ) if the string is empty.

<%int count=10;request.setAttribute("countAttr",new Integer(100));

%>

<!-- intVal is evaluated as 10 --><tst:rtag intVal="<%=count%>"/>

<!-- intVal is evaluated as 1100 --><tst:rtag intVal="1${countAttr}"/>

<!-- strVal is evaluated as "Value is ruppes" --><tst:rtag strVal="Value is <%=count%> ruppes"/>

<!-- strVal is evaluated as "Value is 100 ruppes" -->

SCWCD Material©2007 IBM Corporation

Page 84: SCWCD 1.4 Material

SCWCD Material 84

<tst:rtag strVal="Value is ${countAttr} ruppes"/>

<!-- Results in "Translation Error" (int to byte)--><tst:rtag byteVal="<%=count%>"/>

Action <jsp:useBean>

This action is used to create/use a bean. If the bean with the specified id is already present in specified scope, the same will be used.

Attributes of <jsp:useBean>Attribute

NameDescription

id(mandatory)

Name of the variable, that will be created as a result of <jsp:useBean>.

Since it represents variable name, the id value should be unique for each bean used in a single page.

Scope The scope in which bean will be searched.

Possible Values: page, request, session, application

Default value: pageClass Fully specified class name.

If specified, a bean of this type will be created using default constructor.

If not specified, then no bean will be created. And if bean is not found in specified scope exception will be thrown.

beanName If specified, container uses “Bean Framework” to load bean with specified name.

type Fully specified class name.

Type of the bean to be created. This will not be used to create bean, this will be used as the type during declaration.

So the bean being found/created should be compatible with this type.

Rules If both type & class are specified then, type will be used for declaration of

variable and class will be used for creation (id needed).

SCWCD Material©2007 IBM Corporation

Page 85: SCWCD 1.4 Material

SCWCD Material 85

It’s illegal to specify both class & beanName. Because, both are used to create/find the bean.

Either of class or type is mandatory. If type is not specified, class value will be used for declaration.

If “type” is specified alone then the bean will not be created if it is not existing.

The body of this tag will be executed only if bean is not existing one and is created successfully by this action. And the body of this tag can contain any JSP content.

JSP & Java versions

<jsp:useBean id="sbean" scope="request" class="java.awt.Button"/>

Java Version

java.awt.Button sbean = null;synchronized (request) {

sbean = (java.awt.Button) _jspx_page_context.getAttribute("sbean", PageContext.REQUEST_SCOPE);

if (sbean == null){

sbean = new java.awt.Button();_jspx_page_context.setAttribute("sbean", sbean,

PageContext.REQUEST_SCOPE);}

}

<jsp:useBean id="sbean" scope="request" type="java.awt.Button"/>

Java Version

java.awt.Button sbean = null;synchronized (request) {

sbean = (java.awt.Button) _jspx_page_context.getAttribute("sbean", PageContext.REQUEST_SCOPE);

if (sbean == null){

throw new java.lang.InstantiationException("bean sbean not found within scope");

}

SCWCD Material©2007 IBM Corporation

Page 86: SCWCD 1.4 Material

SCWCD Material 86

}

<jsp:useBean id="sbean" scope="request" class="java.awt.Frame" type="java.awt.Window"/>

Java Version

java.awt.Window sbean = null;synchronized (request) {

sbean = (java.awt.Window) _jspx_page_context.getAttribute("sbean", PageContext.REQUEST_SCOPE);

if (sbean == null){

sbean = new java.awt.Frame();_jspx_page_context.setAttribute("sbean", sbean,

PageContext.REQUEST_SCOPE);}

}

<jsp:useBean id="sbean" scope="request" type="java.awt.Frame" beanName="frame"/>

Java Version

java.awt.Frame sbean = null;synchronized (request) {

sbean = (java.awt.Frame) _jspx_page_context.getAttribute("sbean", PageContext.REQUEST_SCOPE);

if (sbean == null){

try {

sbean = (java.awt.Frame) java.beans.Beans.instantiate(this.getClass().getClassLoader(), "frame");

} catch (ClassNotFoundException exc) {

throw new InstantiationException(exc.getMessage());

} catch (Exception exc) {

throw new ServletException("Cannot create bean of class " + "frame", exc);

}_jspx_page_context.setAttribute("sbean", sbean,

SCWCD Material©2007 IBM Corporation

Page 87: SCWCD 1.4 Material

SCWCD Material 87

PageContext.REQUEST_SCOPE);}

}

<jsp:useBean id="sbean" scope="request" class="java.awt.Button">This is blabbering

</jsp:useBean>

Java Version

java.awt.Button sbean = null; synchronized (request) { sbean = (java.awt.Button) _jspx_page_context.getAttribute("sbean", PageContext.REQUEST_SCOPE); if (sbean == null){ sbean = new java.awt.Button(); _jspx_page_context.setAttribute("sbean", sbean, PageContext.REQUEST_SCOPE); out.write("\r\n"); out.write("\t\t\tThis is blabbering\r\n"); out.write("\t\t"); } }

Action <jsp:setProperty>

Used to set the property of the bean.

Attributes of <jsp:setProperty>Attribute

NameDescription

name(mandatory)

Name of the bean instance defined by <jsp:useBean> or other action. Definition should occur before this tag. Bean can be in any scope.

If not specified, and if this is enclosed in <jsp:useBean> tag then that bean property will be set.

property The name of the property to be set. If this value is “*” then all the request parameters will be set to the corresponding properties of the bean. If the request parameter value is empty the property will not be modified.

param The name of the request parameter whose value should be used to set this property.

If parameter not found or is empty string, property value will not be modified.value Value to be set to this property.

SCWCD Material©2007 IBM Corporation

Page 88: SCWCD 1.4 Material

SCWCD Material 88

Value can be runtime expression.

Rules Both value and param should not be specified. Because both will try to specify

value for the property. Either param or value is mandatory. We need not specify param and value if “property” name matches with request

parameter name.

<jsp:useBean id=”connection” class=”com.myco.myapp.Connection”><jsp:setProperty name=”connection” property=”timeout” value=”33”>

</jsp:useBean>

<jsp:setProperty name=”results” property=”row” value=”<%= i/4 %>” />

Action <jsp:getProperty>

Used to obtain the specified property and send write it to out object.

Attributes of <jsp:getProperty>Attribute

NameDescription

name(mandatory)

Name of the bean instance defined by <jsp:useBean> or other action. Definition should occur before this tag. Bean can be in any scope.

property(mandatory)

Name of the property to get.

Note this is a standard java bean property and doesn’t support nested property (like address.city).

<jsp:getProperty name=”user” property=”name” />

Action <jsp:include>

Helps in inclusion of static and dynamic resources in the output of this page. This is done using RequestDiaptcher.include() so same rules applies. Target resource cannot change headers or status codes.This can <jsp:param> in its body which can specify request parameters for target resource.

SCWCD Material©2007 IBM Corporation

Page 89: SCWCD 1.4 Material

SCWCD Material 89

Attributes of <jsp:include>Attribute Name Description

page(mandatory)

URL of the target resource.

Accepts runtime expression.flush Optional Boolean value. If true, response is flushed before

inclusion.

Default value is false.

<jsp:include page=”urlSpec” flush="true|false">{ <jsp:param .... /> }*</jsp:include>

<jsp:include page=”/templates/copyright.html”/>

Action <jsp:forward>

Forwards request to the target resource using RequestDispatcher.forward(). Same rules will apply.This can <jsp:param> in its body which can specify request parameters for target resource.

Attributes of <jsp:forward>Attribute Name Description

page(mandatory)

URL of the target resource.

Accepts runtime expression.

<jsp:forward page=”urlSpec”>{ <jsp:param .... /> }*</jsp:forward>

<% String whereTo = “/templates/”+someValue; %><jsp:forward page=’<%= whereTo %>’ />

If flush() is called before <jsp:forward> an exception will be thrown on server side and client will be presented with the only data that is flushed.

SCWCD Material©2007 IBM Corporation

Page 90: SCWCD 1.4 Material

SCWCD Material 90

Action <jsp:param>

Used to specify name and value for parameters. This can be used only in <jsp:include>, <jsp:forward> and <jsp:params>. Otherwise exception will be thrown.

Action <jsp:plugin>

Use to specify OLE objects, applets, etc.

Attributes of <jsp:plugin>Attribute Name Description

type Identifies the type of the component; a bean, or an Applet.code As defined by HTML speccodebase As defined by HTML specalign As defined by HTML specarchive As defined by HTML specheight As defined by HTML spec

Accepts runtime expression.hspace As defined by HTML specjreversion Identifies the spec version number of the JRE the component requires

in order to operate; the default is: 1.2name As defined by HTML specvspace As defined by HTML spectitle As defined by HTML specwidth As defined by HTML spec

Accepts runtime expression.nspluginurl URL where JRE plugin can be downloaded for Netscape Navigator,

default is implementation defined.iepluginurl URL where JRE plugin can be downloaded for IE, default is

implementation defined.mayscript As defined by HTML spec

<jsp:plugin type=”applet” code=”Molecule.class” codebase=”/html” ><jsp:params>

<jsp:param name=”molecule” value=”molecules/benzene.mol”/></jsp:params>

<jsp:fallback><p> unable to start plugin </p>

</jsp:fallback></jsp:plugin>

SCWCD Material©2007 IBM Corporation

Page 91: SCWCD 1.4 Material

SCWCD Material 91

Action <jsp:params>

The jsp:params action is part of the jsp:plugin action and can only occur as a direct child of a <jsp:plugin> action. Using the jsp:params element in any other context shall result in a translation-time error.

Action <jsp:fallback>

The jsp:fallback action is part of the jsp:plugin action and can only occur as a direct child of a <jsp:plugin> element. Using the jsp:fallback element in any other context shall result in a translation-time error.

Action <jsp:attribute>

Tag jsp:attribute is useful in specifying parameter values in the body instead of specifying in the starting tag.

This can be used only in custom (Simple and Classic) and for standard tags even though the tag body is declared to be NONE.

<jsp:attribute> can not be used inside <jsp:attribute> Attributes of type JSPFragment can be specified only by using <jsp:attribute>.

And note JSPFragment will not support scriptlet elements. And if scriptlets are present, then it results in translation error.

<jsp:attribute> supports dynamic attributes. If the attribute is declared as request time expression, then the body of

<jsp:attribute> will get evaluated appropriately. If the <jsp:attribute> contains empty body, then the value is evaluated as “”

(empty string). If the <jsp:attribute> specifies the attribute which is already declared in start tag, a

translation error will occur.

Attributes of <jsp:attribute>Attribute Name Description

name(mandatory)

Name of the attribute whose value needs to be specified.

trim True or False. If true, trailing white spaces of the body will get discarded at translation time.

SCWCD Material©2007 IBM Corporation

Page 92: SCWCD 1.4 Material

SCWCD Material 92

Default value is true.

Note: When “trim” is true in <jsp:attribute>, the trailing white spaces are removed during translation. But if the attribute is runtime expression, which results in trailing white spaces then they will not be removed (because white spaces are truncated at translation time not run time).

Assume a tag sbdy, which is “Simple Custom Tag” which can accept “count” attribute and display its body as many times as count attributer indicates.

<tst:sbdy count="3"><jsp:attribute name="count">5</jsp:attribute><jsp:body>

This is simple test<BR> </jsp:body>

</tst:sbdy>

Result: Error, The attribute count specified in the standard or custom action also appears as the value of the name attribute in the enclosed jsp:attribute

<tst:sbdy><jsp:attribute name="count">5</jsp:attribute><jsp:body>

This is simple test<BR> </jsp:body>

</tst:sbdy>

Result: Prints the body 5 times.

More detailed examples for <jsp:attributes> are given in “Custom Tags” section. And the special usage/functionality of <jsp:attribute> in <jsp:element> section.

Action <jsp:body>

The body of a custom/standard tag can be specified using <jsp:body>.

If one or more attributes are specified using <jsp:attribute>, then specifying body with <jsp:body> becomes mandatory. In such cases, if the body is specified, it will be ignored.

SCWCD Material©2007 IBM Corporation

Page 93: SCWCD 1.4 Material

SCWCD Material 93

Assume a tag sbdy, which is “Simple Custom Tag” which can accept “count” attribute and display its body as many times as count attributer indicates.

<tst:sbdy count="3">This is simple test<BR> <jsp:attribute name="count">5</jsp:attribute>

</tst:sbdy>

Result: Error, jsp:attribute must be the sub element of a standard or custom action

<tst:sbdy count="3"><jsp:attribute name="count">5</jsp:attribute>This is simple test<BR>

</tst:sbdy>

Result: Error, Must use jsp:body to specify tag body for &lt;tst:sbdy if jsp:attribute is used.

<tst:sbdy><jsp:attribute name="count">5</jsp:attribute><jsp:body>

This is simple test<BR> </jsp:body>

</tst:sbdy>

Result: Prints the body 5 times.

Action <jsp:element>

This action is used to output an XML element. This action can have optional body which can constitute of <jsp:body> & <jsp:attribute> actions.

<jsp:attribute> in this action body will specify the output XML tag’s name and value.

This action has only one mandatory attribute “name”. Unlike other actions, this value cannot be specified using <jsp:attribute>, because <jsp:attribute> in <jsp:element> body has special meaning.

Attributes of <jsp:attribute>Attribute Name Description

name(mandatory)

The name of the output element. The name value should be as per XML standards and this can QName.

SCWCD Material©2007 IBM Corporation

Page 94: SCWCD 1.4 Material

SCWCD Material 94

Accepts request-time expressions.

<html><body>

<jsp:element name="input"><jsp:attribute name="type">text</jsp:attribute><jsp:attribute name="value">100</jsp:attribute>

</jsp:element></body>

</html>

Output HTML Code

<html><body>

<input type="text" value="100"/></body>

</html>

Action <jsp:text>

Tag <jsp:text> can occur wherever template data can. It contains no attributes.

The function of this tag is to pass its body contents to out. The body can contain EL expressions. No sub-elements or script-elements can occur in the body. Trailing white spaces are not truncated by <jsp:text>

<jsp:text>This is a simple text

</jsp:text>

Result: Displays specified text.

<jsp:text>This is a simple text <jsp:text>Sub text</jsp:text>

</jsp:text>

SCWCD Material©2007 IBM Corporation

Page 95: SCWCD 1.4 Material

SCWCD Material 95

Result: Error

<%int count=10;

%><jsp:text>

This is a simple text <%=count %></jsp:text>

Result: Error

<%int count=10;request.setAttribute("countAttr",new Integer(100));

%>

<jsp:text>This is a simple text ${countAttr}

</jsp:text>

Result: Displays “This is a simple text 100”

SCWCD Material©2007 IBM Corporation

Page 96: SCWCD 1.4 Material

SCWCD Material 96

EL Expressions

EL (Expression Language) target is to replace scripting elements from JSP pages. EL supports the following features:

Available namespace (PageContext attributes) Nested properties and accessors to collections. Relational, logical and arithmetic operators. Extensible mappings to java class’s static methods. Set of implicit objects.

Syntax

EL Expression syntax looks like ${expr}. Where “expr” the expression refers to the scoped attribute with name “expr” or one of the EL implicit object.

EL can be used to access nested properties also. For example, ${curEmp.address.city} refers to the getAddress().getCity() property of the attributed object with name “curEmp”. The attributed object in question can be in any scope. To access attribute in particular scope implicit objects should be used.

Usage

EL as attribute values: EL expressions can be used as value for any attribute, which can accept request time expressions. A translation error will occur if EL is used for attributes, which does not use runtime expressions.

Attribute values can be combination of multiple EL expressions or in combination of EL expression and static text or a single EL expression. In the cases where EL expression is combined with static text or other expressions, first it will get replaced with its String equivalent and then conversion to the attribute type is performed.

In the case where single EL expression is used and target property is some type of Object, then it will pass the object the expression represents.

Examples:<some:tag value="${expr}"/><some:tag value="some${expr}${expr}text${expr}"/>

An EL expression results in an empty string in following cases:

SCWCD Material©2007 IBM Corporation

Page 97: SCWCD 1.4 Material

SCWCD Material 97

When specified scoped attribute not found (nested property, if specified, will be ignored)

When the specified property resulted in a null as a whole, in the middle of the expression evaluation.

EL expression results in an exception only when the specified nested property is invalid.

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%><%@page import="com.test.beans.*"%><%

Address add=new Address("hyd","AP","India");Employee emp=new Employee("kranthi",add,26,1000.234);Employee emp1=new Employee("kranthi",null,26,1000.234);

request.setAttribute("curEmp",emp);request.setAttribute("curEmp1",emp1);

Employee e=new Employee();request.setAttribute("emp",e);

%><html>

<body><%-- The strVal value will be 'India'--%><tst:test strVal="'${curEmp.address.country}'"/>

<%-- The strVal value will be ''Because, curEmp1.address results in null

--%><tst:test strVal="'${curEmp1.address.country}'"/>

<%-- The strVal value will be ''Because there is no attribute with name curEmp2

--%><tst:test strVal="'${curEmp2.address.country}'"/>

<%-- The value of intVal will be 2612Because curEmp.age will result in 26 to which 12 gets appended (=2612)Then conversion to int take place and results 2612.

--%><tst:test intVal="${curEmp.age}12"/>

<%-- emp is of type com.test.Employee and the object stored

SCWCD Material©2007 IBM Corporation

Page 98: SCWCD 1.4 Material

SCWCD Material 98

in request scope is sent to the property emp.--%><tst:test emp="${emp}"/>

</body></html>

Expression in template text: EL expression can be used along with template text directly in JSP or inside the body of the custom or standard tags. Only exception is body of type “tagdependent”. In the case of “tagdependent” bodies expression will be left unevaluated.

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%><%@page import="com.test.beans.*"%><%

Address add=new Address("hyd","AP","India");Employee emp=new Employee("kranthi",add,26,1000.234);request.setAttribute("curEmp",emp);

%><html>

<body>Current employee name is ${curEmp.name} whose age & pay are ${curEmp.age} & ${curEmp.salary}.<BR><BR>

<%-- A custom tag with "scriptless" body--%><tst:sbdy count="1">

Name is ${curEmp.name}</tst:sbdy><BR><BR>

<%-- A custom tag with "tagdependent" body--%><tst:sbdy1 count="1">

Name is ${curEmp.name}</tst:sbdy1>

</body></html>

SCWCD Material©2007 IBM Corporation

Page 99: SCWCD 1.4 Material

SCWCD Material 99

Output

Current employee name is kranthi whose age & pay are 26 & 1000.234.

Name is kranthi

Name is ${curEmp.name}

Operators “[]” & “.”

Dot (.) operatorGiven an expression expr1.expr2 then

Searches for attribute “expr1” if null empty string is returned. If not,

o If the obtained object is a bean, property indicated by “expr2” will be invoked.

o If the obtained object is a Map, then get() will be invoked using “expr2” as key.

Note “expr2” should be a valid java literal (can contain alpha-numeric or underscore ( _ )) and should start with alphabet or underscore ( _ ).

So “lst.2”, “requestScope.num-value” is an invalid expression.

Square ([]) operatorGiven an expression expr1[expr2] then

First expr1 will get evaluated into ans1 If ans1 is null result is empty string. If ans1 is not null expr2 is evaluated into ans2 If ans2 is null then result is empty string.

If ans1 is instance of Map Returns value of ans1.get(ans2) (If “ans2” key is not found or result is null,

then final result is empty string).

If ans1 is an array or an instance of List ans2 is converted into integer. If conversion fails throws an error. Tries to return element at index ans2. If the index is out of bounds

(ArrayIndexOutOfBoundsException or IndexOutOfBoundsException) then null is returned. As a final result empty string is returned.

If any other exception occurs, an error will occur.

SCWCD Material©2007 IBM Corporation

Page 100: SCWCD 1.4 Material

SCWCD Material 100

If the element is found same is returned.

If ans1 is not among Map, List and array Tries to find readable property with name ans2 (as per Java Beans Standard).

If not found error is raised. Note ans2 should be standard property not nested property.

If found the readable property will be executed and result is returned.

Note expr1.identifier1 is equivalent to exprs1[“identifier1”]

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%><%@page import="com.test.beans.*"%><%@page import="java.util.*"%>

<%Address add=new Address("hyd","AP","India");Employee emp=new Employee("kranthi",add,26,1000.234);request.setAttribute("curEmp",emp);

HashMap map=new HashMap();map.put("key_emp",emp);request.setAttribute("empMap",map);

String arr[]={"val1","val2","val3","key_emp"};request.setAttribute("arr",arr);

%>

<html><body>

<%-- Example using dot (.) operator--%>City: ${curEmp.address.city}<BR>

<%--Example using [] operator.Note: ${curEmp["address"]["city"]} is equal to ${curEmp.address.city}--%>City: ${curEmp["address"]["city"]}<BR>

<%-- Identifier "address.city" will not be found as a property in bean

SCWCD Material©2007 IBM Corporation

Page 101: SCWCD 1.4 Material

SCWCD Material 101

resulted from expression "curEmp". Thus this will throw exception.

City: ${curEmp["address.city"]}<BR> --%>

<%-- Accessing map using [] operator --%>City: ${empMap["key_emp"]["address"]["city"]}<BR>

<%-- Accessing array using [] operator --%>Value: ${arr["2"]}<BR>

<%-- Using expression inside [] operator Here arr["3"] will be evaluated into "key_emp" which used as keyto access empMap.

--%>City: ${empMap[arr["3"]]["address"]["city"]}<BR>

<%-- Result: "hyd"

Here literal "city" is taken as string literal a property. Hence this works.--%>City: ${curEmp.address["city"]}<BR><%-- Result: ""

Here city is taken as separate expression (and searches for scoped attribute with name city), which results in null hence result is empty string.--%>City: ${curEmp.address[city]}<BR>

</body></html>

Implicit Objects

Following is the list of implicit objects available for the EL expressions of JSP

pageContext - the PageContext object

SCWCD Material©2007 IBM Corporation

Page 102: SCWCD 1.4 Material

SCWCD Material 102

pageScope - a Map that maps page-scoped attribute names to their values requestScope - a Map that maps request-scoped attribute names to their values sessionScope - a Map that maps session-scoped attribute names to their values applicationScope - a Map that maps application-scoped attribute names to their

values

param - a Map that maps parameter names to a single String parameter value (obtained by calling ServletRequest.getParameter(String name))

paramValues - a Map that maps parameter names to a String[] of all values for that parameter (obtained by calling ServletRequest.getParameterValues(String name))

header - a Map that maps header names to a single String header value (obtained by calling ServletRequest.getHeader(String name))

headerValues - a Map that maps header names to a String[] of all values for that header (obtained by calling ServletRequest.getHeaders(String))

cookie - a Map that maps cookie names to a single Cookie object. Cookies are retrieved according to the semantics of HttpServletRequest.getCookies(). If the same name is shared by multiple cookies, an implementation must use the first one encountered in the array of Cookie objects returned by the getCookies() method. However, users of the cookie implicit object must be aware that the ordering of cookies is currently unspecified in the servlet specification.

initParam - a Map that maps context initialization parameter names to their String parameter value (obtained by calling ServletContext.getInitParameter(String name))

Note all the implicit objects of EL expressions are Maps except “pageContext”.

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%><%@page import="com.test.beans.*"%><%

Address add=new Address("hyd","AP","India");Employee emp=new Employee("kranthi",add,26,1000.234);session.setAttribute("curEmp",emp);

%><html>

<body>Request URI: ${pageContext.request.requestURI} <BR><BR>Parameter ID: ${param.ID}<BR><BR>Parameter values: ${paramValues.values[2]}<BR><BR>Name: ${sessionScope.curEmp.name}

</body>

SCWCD Material©2007 IBM Corporation

Page 103: SCWCD 1.4 Material

SCWCD Material 103

</html>

Since with dot operator second operand should be java literal we cannot use dot operator to fetch attributes in scope maps whose names are not java literals.

For example,requestScope[“user.name”] will fetch request attribute “user.name”

butrequestScope.user.name will fail, because dot operator tries to search “user” attribute in request scope.

Operators & precedence

In all the following operators if any exception occurs during evaluation of below mentioned process, an error will be raised.Following is the list of available arithmetic operators:

Binary Operators: Addition (+), Subtraction (-), Multiplication (*), Remainder (% or mod)

o If either of operand is null return (Long) 0o If one of operand is BigDecimal or Float or Double or String

containing number in decimal or exponential form, then both are converted into BigDecimal and then operator is applied.

o If either of operand is BigInteger then convert both into BigInteger and apply operator.

o Otherwise convert both into Long and apply the operator. Division (/ or div)

o If either of operand is null return (Long) 0o If either of operand is BigDecimal or BigInteger then convert both

into BigDecimal and apply division.o Otherwise convert both into Double and apply operator.

Unary Operators Negation operator (-)

o If the operand is null return (Long) 0o If operand is a string representing number in decimal or

exponential form then it is converted into Double and operator is applied.

o If String in non-decimal and non-exponential form then converted into Long and operator is applied.

o If BigDecimal, BigInteger, Byte, Short, Integer, Long, Float Double then type is retained and operator is applied.

SCWCD Material©2007 IBM Corporation

Page 104: SCWCD 1.4 Material

SCWCD Material 104

Following is the list of Relational Operators Operators <, >, <=, >=, lt, gt, le, ge

o If either of operand is null return falseo If either is BigDecimal then convert both into BigDecimal and use

compareTo().o If either is Float or Double then convert both into Double and use

compareTo().o If either is Byte, Short, Character, Integer or Long then convert

both into Long and use compareTo().o If either of them is String, then comparison will take place

Lexically using String.compareTo().o If either of them is Comparable use compareTo() method of that

operand. Operator = =, !=, eq, ne

o If either of them is null, then == (eq) will return false and != (ne) will return true.

o If either is BigDecimal then convert both into BigDecimal and use equals() (!equals() for != (ne)).

o If either is Float or Double then convert both into Double and use equals ().

o If either is Byte, Short, Character, Integer or Long then convert both into Long and use equals().

o If either of them is Boolean, then both are converted into Boolean and operator is applied.

o If not equals() method is called on first operand.

Following is the list of available logical operators Binary operators (&&, ||, and, or)

o Both operands are converted into Boolean and operator is applied.o The operator stops as soon as the expression can

be determined, i.e., In expression ${A and B and C and D} – if B is false, then only A and B is evaluated.

Unary Operator (!, not)o Convert operand to Boolean and apply operator.

Empty Operator (empty): {empty A} is used to check if “A” is null or empty.

o Returns true if A is null or empty String, array, Collection or Map.

Conditional Operator ${A? B: C} Convert A into Boolean

SCWCD Material©2007 IBM Corporation

Page 105: SCWCD 1.4 Material

SCWCD Material 105

If A is true, evaluate B and return the result If A is false, evaluate C and return the result.

Note, the character version of operators (lt, gt, le … ) are very useful in JSP documents (XML) where we can not use < and > directly.

NOTE: EL expressions are null-friendly. It will substitute null with zero (0) in arithmetic expressions and “false” in logical expressions.

Operator Precedence

Following list shows the precedence of the operators Highest to lowest, left-to-right:

Standard operators [] . (dot) ()

Unary Operators - (unary) not ! empty

Arithmetic Operators * / div % mod + - (binary)

Relational Operators < > <= >= lt gt le ge == != eq ne

Logical Operators && and || or

Conditional Operator ? :

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%><%

request.setAttribute("val1",new Integer(100));request.setAttribute("val2","100");

request.setAttribute("flag","TRUe");%><html>

<body><%-- Result: 400

Note, here even though val2 is a String, it is converted into Longand then addition is performed. If the String was in decimal or exponential form, it would have got converted into Double.

SCWCD Material©2007 IBM Corporation

Page 106: SCWCD 1.4 Material

SCWCD Material 106

--%>Addition: ${val1+val2+100} <BR>

<%-- Conditional operatorResult: 100Note: here flag is a string not Boolean object--%>Result: ${flag? 100: 200}<BR>

<%-- Relational and Logical operatorsResult: true--%>Result: ${val1>50 && val2 gt 80}

<%-- Usage of empty operator Result: 200--%>Result: ${empty flag? 100: 200}<BR>

</body></html>

In order to specify string literal in EL expression used for attribute values we use \ as escape character for double quotes (“), Single quotes (‘) and for \ itself.

Escaping EL Expressions

In order to have EL expressions as template text simply use “\” before EL expressions. Note in template text “\” will not act as escape character other than for EL expressions. But when used attribute values, “\” acts as escape character for all java standard escapable chars and also for EL expressions. Note even in attribute values “\” itself does not need escape character.

<%@ taglib uri="http://kranthi.com/test" prefix="tst" %><%@page isELIgnored="false"%>

<%request.setAttribute("flag","TRUe");

%>

<html><body>

<%--

SCWCD Material©2007 IBM Corporation

Page 107: SCWCD 1.4 Material

SCWCD Material 107

Note both double quotes (") and single quotes (')can be used to specify string literals in EL expressions.

--%><tst:test strVal="${flag?\"val1\":\'val2\'}"/>

<%-- String literal ${ can be directly used in EL expression--%><tst:test strVal="Simple literal ${'${'}"/>

<%-- For using { or } we dont need any special treatmentHere strVal= "Simple { literal }"--%><tst:test strVal="Simple { literal }"/>

<%--To have EL expression as literal use "\" before expression

Here strVal= "Simple literal ${flag}"--%><tst:test strVal="Simple literal \${flag}"/>

<%-- "\" before EL expression is given first preferencethen for others. That’s why strVal for following statements is

Simple literal \${flag}Simple literal \${flag}Simple literal \\${flag}

NOTE: Here \ by itself doesn’t need any escape char, but acts as escape char when used before other known escapable chars.

--%><tst:test strVal="Simple literal \ "/><tst:test strVal="Simple literal \\\${flag}"/><tst:test strVal="Simple literal \\\\${flag}"/>

</body></html>

Data type Conversions

As shown in the above examples, some auto conversions will take place to suit the needs of expression evaluation. Following are the important points to be noted regarding data type conversions:

When converting an Object into String, if object is null, then the result is empty string (“”).

SCWCD Material©2007 IBM Corporation

Page 108: SCWCD 1.4 Material

SCWCD Material 108

When converting a string into character, first character of the string will be used. If the string is empty (char)0 will be the result.

A Number (Byte, Short, Integer, Long, Float, Double), Character & BigDecimal, BigInteger can be converted from one to other automatically.

A Boolean cannot be converted to/from other types other than String. - A null or empty string (“”) conversion to Boolean will result in false.- To convert String into Boolean Boolean.valueOf() is used. Which returns

true if String value is “true” irrespective of case. Otherwise false. To convert any type into String toString() is used. Boxing/Unboxing from primitive to/from their respective wrappers take place

automatically. (This conversion is used during method invocations. Explained later).

Remember, when used for attribute values first the EL expression is converted into String then the JSP standard conversion to the required attribute type will take place.

Reserve Words

Following is the list of reserve wordsand eq gt true instanceofor ne le false emptynot lt ge null divmod

Note currently “instanceof” is not a keyword or being used in EL expressions. But it is a reserve word (for future use) and its usage should be avoided.

SCWCD Material©2007 IBM Corporation

Page 109: SCWCD 1.4 Material

SCWCD Material 109

<%@page isELIgnored="false"%><%

request.setAttribute("flag","TRUe");request.setAttribute("gt","TRUe");request.setAttribute("instanceof","TRUe");

%><html>

<body><%-- Usage of true/false keywordsResult: 100 & 200--%>Value: ${true? 100: 200}<BR>Value: ${false? 100: 200}<BR>

<%-- Invalid usage of keywords. Since gt is keyword it cannot be used as an expression

Value: ${gt}<BR>--%>

<%-- Even though instanceof is reserve word, it works properlyas expression. But it should not be used, as it reserved for future use--%>Value: ${instanceof}<BR>

</body></html>

Functions

We can call java class static functions using EL expressions. For this, in TLD file we need to map a function name to the java static method.

Following example shows how to invoke static function from EL expressions

TLD File

<taglib xmlns="http://java.sun.com/xml/ns/j2ee” version="1.0">... ... ...... ... ...

<function><name>sin</name>

SCWCD Material©2007 IBM Corporation

Page 110: SCWCD 1.4 Material

SCWCD Material 110

<function-class>java.lang.Math</function-class><function-signature>double sin(double)</function-signature>

</function>

<function><name>slp</name><function-class>java.lang.Thread</function-class><function-signature>void sleep(long)</function-signature>

</function></taglib>

JSP File

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%>

<html><body>

<%-- Result = "0.018591582402588132" --%>Result of Sine Method = ${tst:sin(3.123)} <BR>

<%-- Result = "" --%>Result of Sleep Method = ${tst:slp(100)}

</body></html>

The prefix before the method call in the EL expression should match with the prefix of TLD file which contains the function mapping declaration. In the JSP/Tag file documents if the prefix is not specified (Function calls without prefix is possible only in XML documents not in standard JSP file).

Note functions being configured can be of void type and result of expression of such method calls will be empty string.

Disabling/Enabling EL expressions

Since EL expression syntax was not reserved before JSP 2.0, Sun has provided a mechanism by which EL syntaxes can be enabled or disabled. Following table illustrates the default setting related to EL expressions:

SCWCD Material©2007 IBM Corporation

Page 111: SCWCD 1.4 Material

SCWCD Material 111

Type of Document EL Expression Evaluated by defaultJSP Pages (Using web.xml of version <=2.3)

False

JSP Pages (Using web.xml of version >=2.4)

True

For JSP Tag Files True

The default setting for EL expression for JSP files matching specified URL-pattern can be specified in web.xml using <jsp-property-group> element.

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4"><display-name>Custom Tags</display-name><jsp-config>

<jsp-property-group><url-pattern>*.jsp</url-pattern>

<el-ignored>true</el-ignored></jsp-property-group>

</jsp-config>

</web-app>

This default setting can be overridden in JSP file using isELIgnored attribute of “page” directive of JSP files.

<%@page isELIgnored="false"%>

Custom Tags

A custom tag is a user-defined JSP language element. When a JSP page containing a custom tag is translated into a servlet, the tag is converted to operations on a tag handler.

SCWCD Material©2007 IBM Corporation

Page 112: SCWCD 1.4 Material

SCWCD Material 112

Capabilities of custom tags Can be customized via attributes passed from the calling page. Pass variables back to the calling page. Access all the objects available to JSP pages. Communicate with other custom tags. Be nested within one another and communicate via private variables.

TLD (Tag Library Descriptor) File

A TLD file defines and groups different tags (might be java classes or tag files) into a tag library. The TLD files should end with extension “.tld”.

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">

<display-name>web</display-name><tlib-version>1.0</tlib-version><short-name>test</short-name><uri>tst</uri><tag>

<display-name>sbdy</display-name><name>sbdy</name><tag-class>com.test.diff.SimpleBodyTag</tag-class><body-content>scriptless</body-content><attribute>

<name>count</name><required>true</required><type>int</type><rtexprvalue>true</rtexprvalue>

</attribute></tag>

SCWCD Material©2007 IBM Corporation

Page 113: SCWCD 1.4 Material

SCWCD Material 113

<tag><display-name>sbdy1</display-name><name>sbdy1</name><tag-class>com.test.diff.SimpleBodyTag</tag-class><body-content>tagdependent</body-content><attribute>

<name>count</name><required>true</required><type>int</type><rtexprvalue>true</rtexprvalue>

</attribute></tag>

</taglib>

Location of TLD Files

Depending on whether the TLD is application specific or for reusable purposes, they can be present in following two locations:

In application’s /WEB-INF directory or one of its subdirectory. It cannot be in /WEB-INF/classes or /WEB-INF/lib directories. This will be useful in defining application specific tag libraries.

In JAR file’s META-INF directory or one of it’s subdirectory.

TLD files should not be placed in any other location. (Currently tomcat does not raise any errors even if TLD file is placed in any other location).

Accessing TLD libraries

In JSP pages or Tag files TLD files can be accessed using taglib directive in which TLD URI needs to be specified. Container maps this URI to the TLD file resource path (which is nothing but context relative path to TLD file).

Container obtains these mappings (from URI to TLD) in one of the following ways. Following list also defines the precedence given to the map entries.

1. Mapping in web.xml: A mapping from URI to TLD resource path can be explicitly specified in web.xml using <taglib> element. URI can be any string but preferred one would be relative or full URL as shown below.

The TLD resource path mentioned in <taglib-location> should be context relative path pointing to TLD file in the current application (under WEB-INF directory) or context relative path pointing to JAR file that contains TLD file at location /META-INF/taglib.tld.

SCWCD Material©2007 IBM Corporation

Page 114: SCWCD 1.4 Material

SCWCD Material 114

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4">

<display-name>Custom Tags</display-name><jsp-config>

<taglib><taglib-uri>/tags/test</taglib-uri><taglib-location>/WEB-INF/test.tld</taglib-location>

</taglib><taglib>

<taglib-uri>http://kranthi.com/test</taglib-uri><taglib-location>/WEB-INF/test1.tld</taglib-location>

</taglib></jsp-config>

</web-app>

JSP File

<%@ taglib uri="http://kranthi.com/test" prefix="tst" %>

<html><body>

<tst:test byteVal="10"> </tst:test></body>

</html>

2. Implicit Map Entries from TLDs: Container will search for all TLD files (with extension .tld) under application’s /WEB-INF directory and its sub-directory & in /META-INF directory and its subdirectory of all JAR files present under application’s /WEB-INF/lib directory. In each of these TLD files, if <uri> is specified (and if its not defined in web.xml), then a new map entry is made with specified uri and current TLD file location.

SCWCD Material©2007 IBM Corporation

Page 115: SCWCD 1.4 Material

SCWCD Material 115

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">

<display-name>web</display-name><tlib-version>1.0</tlib-version><short-name>/tags/test</short-name><uri>http://kranthi.com/test</uri><tag>

<display-name>sbdy</display-name><name>sbdy</name><tag-class>com.test.diff.SimpleBodyTag</tag-class><body-content>scriptless</body-content><attribute>

<name>count</name><required>true</required><type>int</type><rtexprvalue>true</rtexprvalue>

</attribute></tag>

</taglib>

3. Implicit Map Entries From Container: The container may also provide URI

mappings for the well-known tag libraries. Container should provide the implementation of these libraries. It is preferred not to use these URI as they might be container specific.

The URI mentioned in the “uri” attribute of “tablib” directive is interpreted in following ways:

1. Absolute URI (A complete URL including protocol): URI to TLD map (mentioned above) will be searched, if found, it is used. If not found error will be raised.

2. Relative URI (starting with /): URI to TLD map will be searched, if found, it is used. If not found this path should be the TLD resource path (that is context relative path pointing to TLD or to JAR file having /META-INF/taglib.tld file).

3. Relative URI (not starting with /): URI to TLD map will be searched, if found, it is used. If not found this path is interpreted relative to the current JSP or tag file. For example, “../../WEB-INF/tags/test.tld”.

SCWCD Material©2007 IBM Corporation

Page 116: SCWCD 1.4 Material

JSPTag

Tag SimpleTag

IterationTag

BodyTag

SCWCD Material 116

<%-- Example for including TLD file in WEB-INF directory --%><%@ taglib uri="/WEB-INF/test.tld" prefix="tst" %>

<%-- Example for including TLD file from a jar fileIn below example, test.jar contains file /META-INF/taglib.tld

--%><%@ taglib uri="/WEB-INF/lib/test.jar" prefix="tst" %>

Life-Cycle

A custom tag handler must implement javax.servlet.jsp.tagext.Tag or javax.servlet.jsp.tagext.SimpleTag interface. Tag handlers implementing Tag interface are called “Classic Tag Handlers”. Depending on the different levels of support given by the container, Tag interface is extended by IterationTag and BodyTag. Following diagram shows the hierarchy of the base interfaces of all base tag handler interfaces

SCWCD Material©2007 IBM Corporation

Page 117: SCWCD 1.4 Material

SCWCD Material 117

“Classic Tag” Vs “Simple Tag”

“Classic Tag” Vs “Simple Tag”Classic Tags Simple Tags

Caching Instances of classic tags are cached and reused for efficiency.

For every usage a new instance is created and released for garbage collection.

Context setPageContext() accepts PageContext. Because it is designed for the servlet environment.

setJspContext() accepts JspContext (which can be type casted to PageContext). This are designed for neutral environment.

Parent setParent() accepts Tag which can be used for communication with parent tag classes.

setParent() accepts JspTag which can be used for communication with parent tag classes.

Since “Classic Tags” accepts Tag only as parent, javax.servlet.jsp.tagext.TagAdapter class is used by generated code to wrap “simple Tag” with “Tag” wrapper and passes this wrapper as parent to “Classic Tag Handler”. So that a “Classical Tag” can be parent to “Simple Tag” and vice versa.

Note that “Simple Tag” accepts JspTag, which means it can accept both “Classic Tags” and “Simple Tags” as it parent.

Body (tag Variables)

Accepts body types – none, tagdependent, scriptless and JSP.

The body content is received only by “Body Classic Tags” that to on conditional basis (explained later).

Since JSP content (scripting-elements) are accepted as body content, tag variables can be used very efficiently.

“Simple Tags” receives body content as JSP fragment and JSP fragment doesn’t accept scripting-elements. Hence “Simple Tags” accepts body types – none, tagdependent and scriptless. But not JSP.

Since JSP content type is not accepted as body content, usage of variables (explained in “Tags that define Variables” in “Types of Custom Tags” section) is not much advantageous. The variables will act as good as scoped-attributes.

Life Cycle Depending on the type of classical tag – the life cycle varies from 2 to 4 action methods.

Consists of simple life cycle with a single action method. The iteration and everything has to be taken care here itself.

Control By controlling the return value life cycle action method – doEndTag() we can control the further page evaluation.

“Simple Tags” can through javax.servlet.jsp.SkipPageException to skip the rest of the page. This is equivalent to “Classic Tag” doEndTag() returning SKIP_BODY.

SCWCD Material©2007 IBM Corporation

Page 118: SCWCD 1.4 Material

SCWCD Material 118

“Classic Tag” Standard Type (implementing javax.servlet.tagext.Tag)

As shown in the figure above there are only two life-cycle action methods – doStartTag() & doEndTag().

The action method doStartTag() can return only two values - Tag.EVAL_BODY_INCLUDE & Tag.SKIP_BODY.

If doStartTag() returns Tag.EVAL_BODY_INCLUDE then the body is evaluated and output will be sent current “out” JspWriter. Otherwise the body will be skipped.

The action method doEndTag() can return only two values – Tag.SKIP_PAGE or Tag.EVAL_PAGE.

If the action method doEndTag() return Tag.EVAL_PAGE rest of the page will get evaluated otherwise it will not, it simply returns the response with current content. Tag.SKIP_PAGE will make container not to call doEndTag() of enclosing tags.

Since “Classic Tag Hanlder” instances may get cached, the doEndTag() should reset the tag handler instance state.

SCWCD Material©2007 IBM Corporation

setPageContext()setParent()

Attribute Setters

doStartTag() **

Evaluate Body

doEndTag() **

EVAL_BODY_INCLUDE

SKIP_BODY

End PageEvaluation.

Evaluate Restof the Page.

SKIP_PAGEEVAL_PAGE

release() **

Page 119: SCWCD 1.4 Material

setPageContext()setParent()

Attribute Setters

doStartTag() **

Evaluate Body

doEndTag() **

EVAL_BODY_INCLUDE

SKIP_BODY

End PageEvaluation.

Evaluate Restof the Page.

SKIP_PAGEEVAL_PAGE

release() **

doAfterBody() **

SKIP_BODY

EVAL_BODY_AGAIN

SCWCD Material 119

Other action method “release()” is called to release the state of tag handler but before that there might be multiple calls to doStartTag() and doEndTag() (as the instance is cached and reused).

“Classic Tag” Iteration Type (implementing javax.servlet.tagext.IterationTag)

SCWCD Material©2007 IBM Corporation

Page 120: SCWCD 1.4 Material

SCWCD Material 120

Interface “IterationTag” (javax.servlet.jsp.tagext.IterationTag) extends “javax.servlet.jsp.tagext.Tag” interface & defines one more constant – EVAL_BODY_AGAIN and one more action method – doAfterBody().

The life cycle is similar to “standard Classic Tag Handler” with the only difference that

o If the doStartTag() returns EVAL_BODY_INCLUDE then after body evaluation to current “out” JspWriter, action method doAfterBody() will get called.

o Action method doAfterBody() can return only two values EVAL_BODY_AGAIN or SKIP_BODY.

o If EVAL_BODY_AGAIN is returned the body will be reevaluated and doAfterBody() will be called again. If SKIP_BODY is returned doEndTag() gets called.

“Classic Tag” Body Type (implementing javax.servlet.tagext.BodyTag)

SCWCD Material©2007 IBM Corporation

setPageContext()setParent()

Attribute Setters

doStartTag() **

Evaluate Body

doEndTag() **

EVAL_BODY_INCLUDE

SKIP_BODY

End PageEvaluation.

Evaluate Restof the Page.

SKIP_PAGE EVAL_PAGE

release() **

doAfterBody() **

SKIP_BODY

EVAL_BODY_AGAIN

setBodyContent() doInitBody()**

EVAL_BODY_BUFFERED

Page 121: SCWCD 1.4 Material

SCWCD Material 121

BodyTag (javax.servlet.jsp.tagext.BodyTag) extends javax.servlet.jsp.tagext.IterationTag and defines one extra constant – EVAL_BODY_BUFFERED and method setBodyContent() and an additional action method doInitBody().

BodyTag works exactly like IterationTag others than following differenceso doStartTag() can return EVAL_BODY_BUFFERED also. In this case

setBodyContent() will be called with the BodyContent object representing body content. Then doInitBody() will be called (a void method). Then body gets evaluated and same flow of IterationTag continues.

SCWCD Material©2007 IBM Corporation

Page 122: SCWCD 1.4 Material

SCWCD Material 122

TLD File

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" version="1.0">... ... <tag>

<display-name>ClsTest</display-name> <name>ctest1</name>

<tag-class>com.test.CLifeCycle</tag-class><body-content>JSP</body-content>

<attribute><name>name</name><required>true</required><type>String</type>

</attribute></tag>

</taglib>

SCWCD Material©2007 IBM Corporation

Page 123: SCWCD 1.4 Material

SCWCD Material 123

TAG Handler Code

public class CLifeCycle implements Tag{

private Tag parent;private String name;

public void setPageContext(PageContext ctx){

System.out.println("setPageContext");}

public void setParent(Tag parent){

System.out.println("setParent");this.parent=parent;

}

public Tag getParent(){

System.out.println("getParent");return parent;

}

public int doStartTag() throws JspException{

System.out.println("doStartTag");return Tag.EVAL_BODY_INCLUDE;

}

public int doEndTag() throws JspException{

System.out.println("doEndTag");return Tag.EVAL_PAGE;

}

public void release(){

System.out.println("release");}

public void setName(String name){

System.out.println("setName");this.name=name;

SCWCD Material©2007 IBM Corporation

Page 124: SCWCD 1.4 Material

SCWCD Material 124

}}

JSP Code

<html><head>

<title>Simple classic test page</title></head>

<body><tst:ctest1 name="kk">

This is simple test <%="kranthi"%></tst:ctest1>

<tst:ctest1 name="kk1">This is simple test <%="kranthi"%>

</tst:ctest1>

</body></html>

Page Context

PageContext object is available in JSP pages as implicit variable “pageContext” and it is available to custom tags in JSP pages, which is passed by the container using setPageContext() of Tag class and setJspContext() of SimpleTag class.

PageContext class extends JSPContext. JspContext abstracts all the information that is not specific to the HTTP, note JSP can be used in non-servlet environment also.

Based on functionality methods of PageContext can be grouped as follows:

Attribute related methods: These methods provide single point mechanism to access attributes from any scope.

Object findAttribute(String name)

SCWCD Material©2007 IBM Corporation

Page 125: SCWCD 1.4 Material

SCWCD Material 125

Searches for the specified attribute in all scopes in order – page, request, session (if applicable) & in application scopes. If not found null is returned.

Object getAttribute(String name)

Returns specified attribute from page scope. If not found null is returned.

Object getAttribute(String name, int scope)

Return the object associated with the name in the specified scope or null if not found.

Scope one of the following constants defined in PageContextPAGE_SCOPE, REQUEST_SCOPE, SESSION_SCOPE OR

APPLICATION_SCOPE

Enumeration getAttributeNamesInScope(int scope)

Enumerate all the attributes in a given scope.

int getAttributesScope(String name)

Get the scope where a given attribute is defined. Returns 0 if not found.

void removeAttribute(String name)

Remove the object reference associated with the given name from all scopes. Does nothing if there is no such object.

void removeAttribute(String name, int scope)

Remove the object reference associated with the specified name in the given scope. Does nothing if there is no such object.

void setAttribute(String name, Object value)

Register the name and value specified with page scope semantics. If the value passed in is null, this has the same effect as calling removeAttribute(name, PageContext.PAGE_SCOPE).

void setAttribute(String name, Object value, int scope)

SCWCD Material©2007 IBM Corporation

Page 126: SCWCD 1.4 Material

SCWCD Material 126

Register the name and value specified with appropriate scope semantics. If the value passed in is null, this has the same effect as calling removeAttribute(name, scope).

EL Expression Relation Methods: Using these methods programmers can evaluate EL expressions dynamically.

ExpressionEvaluator getExpressionEvaluator()

Provides programmatic access to the ExpressionEvaluator that can parse EL expressions.

VariableResolver getVariableResolver()

Returns VariableResolver that is needed to parse EL expressions by ExpressionEvaluator. VariableResolver is used to resolved variable names (implicit objects also).

Write access Method

JspWriter getOut()

The current value of the out object (a JspWriter).

Methods to manage nested JSP Writers

JspWriter pushBody(Writer writer)

This method wraps the specified writer with JSP Writer class, saves current JspWriter represented by “out” attribute and updates “out” attribute in page-scope-attribute-namespace of JSP Context with wrapped instance. So that the next call to getOut() will return the wrapped instance.

Note: This will not have any effect on implicit object “out” or the static text going to response stream in the JSP page. Its only getOut() which will return different instance (wrapped instance).

BodyContent pushBody()

Similar to pushBody(Writer) but return value is BodyContent and the writer will be maintained internally in memory.

JspWriter popBody()

SCWCD Material©2007 IBM Corporation

Page 127: SCWCD 1.4 Material

SCWCD Material 127

Return the previous JspWriter "out" saved by the matching pushBody(), and update the value of the "out" attribute in the page scope attribute namespace of the JspContext.

Methods For Accessing implicit objects of JSP

Exception getException()

The current value of the exception object (an Exception). Applicable only for error pages.

Object getPage()

The current value of the page object (In a Servlet environment, this is an instance of javax.servlet.Servlet).

ServletRequest getRequest()

The value of the request object. Note, in JSP the “request” implicit object is an instance of HttpServletRequest (so that you can get request parameters and other http specific operations).

ServletResponse getResponse()

The current value of the response object. Note, in JSP the “response” implicit object is an instance of HttpServletResponse (so that you can set Http headers and perform other http specific operations).

ServletConfig getServletConfig()

The ServletConfig instance.

ServletContext getServletContext()

The ServletContext instance.

HttpSession getSession()

The current value of the session object (an HttpSession).

Note: getOut() is specified before itself. And one more implicit object missing is pageContext itself.

SCWCD Material©2007 IBM Corporation

Page 128: SCWCD 1.4 Material

SCWCD Material 128

All the implicit objects are maintained as attributes in pageContext name table (that is in page scope) which can be accessed using following attribute names which are constants of PageContext class

PAGE, PAGECONTEXT (to store itself), REQUEST, RESPONSE, CONFIG, SESSION, OUT, APPLICATION & EXCEPTION

One more function related to implicit objects is

ErrorData getErrorData()

ErrorData instance containing information about the error, as obtained from the request attributes, as per the Servlet specification. If this is not an error page (that is, if the isErrorPage attribute of the page directive is not set to "true"), the information is meaningless.

Methods for including and forwarding request

void forward(String uri)

Same rules as that of <jsp:forward>

void include(String uri)void include(String uri, boolean flush)

Just like <jsp:include>

Method For Handling Exceptions

void handlePageException(Exception ex) //for backward compatibilityvoid handlePageException(Throwable th)

In the case of exception/error above methods can be used to forward the request to the error page. These methods are specially useful in custom tags. A same rule of response committing applies here.

Container Method

void initialize(Servlet servlet, ServletRequest request, ServletResponse response, String errorPageURL, boolean needsSession, int bufferSize, boolean autoFlush)

SCWCD Material©2007 IBM Corporation

Page 129: SCWCD 1.4 Material

SCWCD Material 129

Called by container to initialize page context object. JSP or custom tag authors should not call this method.

void release()

Called by container to release page context object for garbage collection or reuse. JSP or custom tag authors should not call this method.

Types of Custom Tags

Depending on the features/customization/functionality supported by custom tags, they can be divided into following three groups

1. Tags With Attributes2. Tags with Body3. Tags that define variables

Tags With Attributes

Tags can be declared to accept parameters. For each of the declared attribute there should be corresponding setter. These parameters can be divided into following groups

Simple Attributes

SCWCD Material©2007 IBM Corporation

Page 130: SCWCD 1.4 Material

SCWCD Material 130

Container evaluates these attributes before being passed to the tag. The values for these attributes can be constants or EL expressions. These values can also be passed using <jsp:attribute>. Note for attribute values scripting-expressions or EL Expressions can be used only when <rtexprvalue> sub-element of corresponding <attribute> tag in TLD is specified as true. If <rtexprvalue> is not specified it is considered to be true.

Fragment Attributes

Fragment is a portion of JSP code that will be passed as attribute to the tag. Fragment can be treated as a template that can be evaluated by the tag handler for zero or multiple times.

Fragment attribute should be declared by using fragment (as true) sub-element of TLD element and values can be specified only by using <jsp:attribute>. Remember, attribute cannot have < or > symbols. The body of the <jsp:attribute> specifying fragment should be static text or standard JSP tags and custom tags. But it cannot contain scripting elements. The content of the fragment can have EL expressions.

At translation time, container generates an implementation of javax.servlet.jsp.tagext.JspFragment abstract class capable of executing the specified fragment. To communicate with fragments, tag handlers can use attributes in JspContext.

Note: Its container dependent on container whether to generate multiple or single class for multiple fragments in a page.

Dynamic Attributes

These are the attributes, which are not specified in the tag declaration. Tag handlers whose attribute names cannot be determined at development time use these attributes. EL expressions or <jsp:attribute> can be used to specify these values.

In order to accept dynamic attributes by tag handler, it should follow below two conditions:

The tag handler must implement javax.servlet.jsp.tagext.DynamicAttributes interface (and uses its setDynamicAttribute() method to accept dynamic attributes)

In TLD file <dynamic-attributes> should be set to true under corresponding <tag> element.

All dynamic attributes accept expressions. And since dynamic attributes accepting method setDynamicAttribute() accepts value as java.lang.Object, the script-expression if used should result in an Object (not as primitive). Otherwise error will be thrown.

SCWCD Material©2007 IBM Corporation

Page 131: SCWCD 1.4 Material

SCWCD Material 131

Note: Whenever <rtexprvalue> is true, the type of the attribute (if not primitive) should be fully specified class name.

TLD File

<taglib xmlns="http://java.sun.com/xml/ns/j2ee version="2.0">.. .. .... .. .. <tag> <!—Declaring a Tag -->

<display-name>AttTest</display-name> <name>test1</name>

<tag-class>com.test.TestTag</tag-class>

<body-content>empty</body-content> <!—Declaring tag to have empty body only -->

<attribute> <!—Declaring a simple attribute --><name>rowCount</name><required>false</required><rtexprvalue>true</rtexprvalue> <!—Declaring a attribute to accept

runtime expressions – both EL & Script-elemnet --><type>int</type>

</attribute>

<attribute> <!—Declaring a JSP fragment attribute --><name>rowButton</name><required>true</required><fragment>true</fragment>

</attribute>

<dynamic-attributes>true</dynamic-attributes> <!—Declaring tag to accept dynamic attributes -->

</tag> </taglib>

Java Code

public class TestTag extends SimpleTagSupport implements DynamicAttributes{

private String heading="";private int rowCount=2;private JspFragment rowButton=null;private HashMap dynAtt=new HashMap();

SCWCD Material©2007 IBM Corporation

Page 132: SCWCD 1.4 Material

SCWCD Material 132

public void doTag() throws JspException,IOException{

StringWriter res=new StringWriter();res.append("<TABLE Border=\"1\"><TR><TD colspan=\"2\">");res.append(heading);res.append("</TD></TR>");

for(int i=0;i<rowCount;i++){

res.append("<TR><TD>");rowButton.invoke(res); //Invoking & getting result of JSP

//Fragment attributeres.append("</TD><TD>");res.append(""+i);res.append("</TD></TR>");

}res.append("</TABLE>");res.flush();getJspContext().getOut().write(res.toString());

}

public void setHeading(String s){

heading=s;}

//Declaring setter method for JSP Fragment attributepublic void setRowButton(JspFragment rowButton){

this.rowButton=rowButton;}

//Declaring setter method for JSP Fragment attributepublic void setRowCount(int rowCount){

if(rowCount<=0)throw new IllegalArgumentException("Invalid row count

specified: "+rowCount);

this.rowCount=rowCount;}

//Dynamic attributes accepting. Note: in this example, these attributes are not usedpublic void setDynamicAttribute(String uri,String name,Object value)

throws JspException

SCWCD Material©2007 IBM Corporation

Page 133: SCWCD 1.4 Material

SCWCD Material 133

{dynAtt.put(name,value);System.out.println("Dynamic Attribute: "+name+"===>"+value);

}}

JSP File

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%> <%-- Declaring page to parse EL expressions--%><%

request.setAttribute("count",new Integer(10));String value="Simple Value";

%>

<html><body>

First Grid:<BR><%-- Using above created tag--%><tst:test1 rowCount="${count}" datt1="value1" datt2="<%=value%>" datt3="$

{count}"><jsp:attribute name="rowButton"> <%—Specifying JSP fragment. Here

is just static text (no JSP standard or custom tags in fragment body) --%>

<input type="button" value="Click"/></jsp:attribute>

</tst:test1></body>

</html>

Attributes using <jsp:attribute>

Passing the attributes directly as attribute or by using <jsp:attribute> will not make any difference. Note even when <jsp:attribute> is used script-expression or EL expression can be used only for attributes which are declared to be runtime expression in TLD.

Tags with Body

Body of the tag can contain custom tags, JSP standard tags and static text and EL expressions. The body of a tag can be of three types – according to the possible values of <body-content> tag.

SCWCD Material©2007 IBM Corporation

Page 134: SCWCD 1.4 Material

SCWCD Material 134

empty: Corresponding JSP tag can not have any body, not even white spaces. tagdependent: The body of the tag is expected to be evaluated by tag handler

itself. Even the EL expression will not get parsed. And all the script elements and custom tags will be ignored in this sort of bodies.

scriptless: In this type of body, script elements will generate translation error. This type of body can contain EL expressions, static text and custom tags. It is error to use script-expression to specify attribute values for child custom tag attributes, which accepts runtime expressions.

JSP: Specified the body of the tag will have nested JSP code. SimpleTag treats the body of the tag as JSPFragment and JSPFragment does not support scriptlet elements. Hence JSP body type can be used only with classic tags otherwise translation error will be raised.

Note: Only JSP body type can contain scriptlet elements.

JSP Code

public class BodyTest extends SimpleTagSupport{

private int count;

public void doTag() throws JspException,IOException{

JspFragment body=getJspBody();for(int i=0;i<count;i++)

body.invoke(null); //Evaluating/Executing body of tag}

public void setCount(int count){

this.count=count;}

}

SCWCD Material©2007 IBM Corporation

Page 135: SCWCD 1.4 Material

SCWCD Material 135

TLD File

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" version="2.0">. . . . . . . . . . . . <tag>

<display-name>BodyTest</display-name> <name>test2</name>

<tag-class>com.test.BodyTest</tag-class><body-content>tagdependent</body-content> <!—Declaring Body type -->

<attribute><name>count</name><required>true</required><type>int</type><rtexprvalue>true</rtexprvalue>

</attribute></tag>

<tag><display-name>BodyTest1</display-name>

<name>test3</name><tag-class>com.test.BodyTest</tag-class><body-content>scriptless</body-content> <!—Declaring Body type -->

<attribute><name>count</name><required>true</required><type>int</type><rtexprvalue>true</rtexprvalue>

</attribute></tag>

</taglib>

SCWCD Material©2007 IBM Corporation

Page 136: SCWCD 1.4 Material

SCWCD Material 136

JSP Code

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%><%@page import="java.awt.Button"%>

<%request.setAttribute("count",new Integer(100));request.setAttribute("button",new Button("test button"));int count=10;

%>

<html>

<body><%-- tagdependent body. Here all script-elements and custom tags

are ignored. EL expressions will be left unparsed--%><tst:test2 count="2">

This is a simple test body <%=count%> & ${count}<jsp:getProperty name="button" property="label"/>

</tst:test2>

<BR><BR><BR><%-- scriptless body. Here Script-elements will raise translation

errors. Custom tags & EL expressions are evaluated. --%><tst:test3 count="2">

This is a simple test2 body ${count}<jsp:getProperty name="button" property="label"/>

</tst:test3></body>

</html>

Note whenever attributes are specified using <jsp:attributre>, the body of the tag must be specified using <jsp:body> otherwise a translation error will be raised.

<tst:test2><jsp:attribute name="count">3</jsp:attribute><jsp:body>

This is a simple test body ${count}<jsp:getProperty name="button" property="label"/>

</jsp:body></tst:test2>

SCWCD Material©2007 IBM Corporation

Page 137: SCWCD 1.4 Material

SCWCD Material 137

Note declaring body-type in TLD is mandatory.

Example for Classic Tag using JSP body type

TLD File

<tag><display-name>cbdy</display-name>

<name>cbdy</name><tag-class>com.test.diff.ClassicBodyTag</tag-class><body-content>JSP</body-content>

<attribute><name>count</name><required>true</required><type>int</type><rtexprvalue>true</rtexprvalue>

</attribute></tag>

Classic Tag Source Code

public class ClassicBodyTag extends TagSupport{

private int count;private int curCount=0;

public void setCount(int count){

this.count=count;}

public int doStartTag() throws JspException{

curCount=0;return EVAL_BODY_INCLUDE;

}

public int doAfterBody() throws JspException{

curCount++;if(curCount<count)

return EVAL_BODY_AGAIN;

SCWCD Material©2007 IBM Corporation

Page 138: SCWCD 1.4 Material

SCWCD Material 138

return SKIP_BODY;}

}

JSP Code

<%String simpleText="This is simple text";

%>

<html><head>

<title>Simple classic test page</title></head>

<body><tst:cbdy count="3">

Expression value is : <%=simpleText%><BR></tst:cbdy>

</body></html>

Tags that define Variables

Attributes are the input to the tag handlers similarly variables are the means by which tag handlers can return/communicate with the calling page. A tag handler can be declared to support variables using <variable> tag of <tag> element in TLD file. The scope of this variable in the JSP page can be specified as one of the values in the following table

Scope DescriptionNESTED Variables are available from the start of the tag to the end of the tag.AT_BEGIN

The variable is available from the start of the tag to the end of the enclosing tag. If enclosing tag is not there, till the end of the page.

AT_END Available after the end of the tag till end of enclosing tag. If enclosing tag is not there, till the end of the page.

It is the responsibility of the tag handler to set the value in one of the standard scopes (page, request, session or application) as an attribute with the name of the variable. Note this value has to be removed explicitly, irrespective of the scope defined in the TLD. The scope of the variable just determines when and where the variable has to be declared in the generated servlet code.

SCWCD Material©2007 IBM Corporation

Page 139: SCWCD 1.4 Material

SCWCD Material 139

The scope value for a variable implies what methods may affect its value and thus where synchronization is needed as illustrated by the table below.

Variable Synchronization Points

doStartTag() doInitBody() doAfterBody() doEndTag() doTag()

Tag AT_BEGIN, NESTED

AT_BEGIN, AT_END

IterationTag AT_BEGIN, NESTED

AT_BEGIN, NESTED

AT_BEGIN, AT_END

BodyTag AT_BEGIN, NESTED

AT_BEGIN, NESTED

AT_BEGIN, NESTED

AT_BEGIN, AT_END

SimpleTag AT_BEGIN, AT_END

Classic Tags and Simple Tag Variables

Variables are particularly useful when the body of tag is of JSP content. Because, they can be used in scripting elements as though they are declared in same page. Hence variables are more useful for Classic Tags (Remember, Simple Tags does not support JSP content and scripting elements in its body).

For Simple Tags variables are as good as scoped attributes. The only exception is the variables declared by non-nested tags. Because these variables can be used by scripting elements after the Simple tag body.

Naming Variables

Custom JSP tags can name variables being defined in following two ways By defining name using <name> element of <variable> tag. By using <name-from-attribute> element of <variable> tag. The name specified

by this element, indicates the attribute whose value should be used as variable name.

Note: Its translation error to have more than one variable with the same name.

Variable Types

Since container retrieves variable value from scoped attributes, the type of variables should be Object type it cannot be primitive (instead use wrapper), otherwise translation error will occur.

SCWCD Material©2007 IBM Corporation

Page 140: SCWCD 1.4 Material

SCWCD Material 140

If the type of variable is not specified, the default type java.lang.String.

The type of the variable being specified can be fully specified name or short name. If the short name is specified it should be valid type according to the imports as mentioned in “page” directive of the corresponding page.

TLD File

<tag><display-name>iterate</display-name><name>iterate</name><tag-class>com.test.IterationTag</tag-class><body-content>JSP</body-content>

<attribute><name>counter</name><required>true</required><type>String</type>

</attribute>

<attribute><name>count</name><required>true</required><type>int</type>

</attribute>

<attribute><name>varName</name><required>true</required><type>String</type>

</attribute>

<attribute><name>endValue</name><required>true</required><type>String</type>

</attribute>

<variable><name-from-attribute>counter</name-from-attribute><scope>NESTED</scope><variable-class>Integer</variable-class>

</variable>

<variable><name-from-attribute>varName</name-from-attribute><scope>AT_BEGIN</scope>

</variable>

<variable><name-from-attribute>endValue</name-from-attribute><scope>AT_END</scope>

SCWCD Material©2007 IBM Corporation

Page 141: SCWCD 1.4 Material

SCWCD Material 141

<variable-class>Integer</variable-class></variable>

</tag>

Tag Handler Code

public class IterationTag extends TagSupport{

private int count;private int curCount=0;private String counter;private String varName;private String endValue;

public void setCount(int count){

this.count=count;}

public int doStartTag() throws JspException{

curCount=0;pageContext.setAttribute(varName,"Simple Variable from iteration tag:

"+count,PageContext.REQUEST_SCOPE);

//the following statement is needed to care of counter at start of looppageContext.setAttribute(counter,new Integer(0),PageContext.REQUEST_SCOPE);return EVAL_BODY_INCLUDE;

}

public int doAfterBody() throws JspException{

curCount++;pageContext.setAttribute(counter,new

Integer(curCount),PageContext.REQUEST_SCOPE);if(curCount<count)

return EVAL_BODY_AGAIN;

return SKIP_BODY;}

public int doEndTag() throws JspException{

pageContext.setAttribute(endValue,new Integer(curCount),PageContext.REQUEST_SCOPE);

return super.doEndTag();}

public void setCounter(String counter){

this.counter=counter;}

SCWCD Material©2007 IBM Corporation

Page 142: SCWCD 1.4 Material

SCWCD Material 142

public void setVarName(String varName){

this.varName=varName;}

public void setEndValue(String endValue){

this.endValue=endValue;}

}

JSP Code

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%>

<html>

<body><tst:iterate count="3" counter="i" varName="outerVar" endValue="outerEnd">

This is outer loop iteration: <%=i%><BR><tst:iterate count="4" counter="j" varName="innerVar"

endValue="innerEnd"> &nbsp;&nbsp;&nbsp;&nbsp;This is inner loop iteration: <%=j%> of outer loop:

<%=i%><BR>

</tst:iterate><%-- Following results in compile error, becos j scope is NESTED

Value of j is <%=j %> --%> Value of innerEnd: <%=innerEnd%> and innerVar= <%=innerVar%><BR> <%-- Following results in compile error, becos outerEnd scope is AT_END Value of outerEnd: <%=outerEnd%> and --%> outerVar= <%=outerVar%><BR>

</tst:iterate>

<%-- Following results in compile error, becos nesteg tag variables scope ends With the end of enclosing tag Value of innerEnd: <%=innerEnd%> and innerVar= <%=innerVar%><BR> --%> Value of outerEnd: <%=outerEnd%> and outerVar= <%=outerVar%><BR>

</body>

</html>

SCWCD Material©2007 IBM Corporation

Page 143: SCWCD 1.4 Material

SCWCD Material 143

Note: In the case of “Simple Tags” since no scripting elements are allowed inside tag, the only way to access them is using EL expressions, which is as good as using scoped attributes. The only difference is non-NESTED variables declared non-nested “simple tags” can be accessed in scripting elements after the tag end.

Variables without declaration

A variable can be defined not to be declared in the source JSP file by using <declare> element of <variable> element in the TLD as follows:

<tag><display-name>varTest</display-name><name>varTest</name><tag-class>com.test.VarTest</tag-class><body-content>JSP</body-content><attribute>

<name>varName</name><required>true</required><type>java.lang.String</type>

</attribute>

<variable><name-from-attribute>varName</name-from-attribute><scope>NESTED</scope><variable-class>Integer</variable-class>

<declare>false</declare></variable>

</tag>

By defining <declare> as false, this variable will not be defined in the source page. Thus these variables can no more be used in scripting elements directly. They should be treated as scoped attributes.

TagExtraInfo Class

TagExtraInfo class (javax.servlet.jsp.tagext.TagExtraInfo) can be used to provide the extra information (variable information), which is not specified in the TLD file. This class can be used for the following purposes:

To define additional variable information (dynamic variables) at the translation time only.

To provide translation time validation of the tag attributes.

Following are the methods and their description

SCWCD Material©2007 IBM Corporation

Page 144: SCWCD 1.4 Material

SCWCD Material 144

final TagInfo getTagInfo()

Provides the tag information like tag name, tag class, tag library as a whole, whether dynamic attributes are supported, body content type, etc.

final void setTagInfo()

Sets the TagInfo for this object. The JSP translator calls this method.

VariableInfo[] getVariableInfo(TagData data)

TagData represents attribute information and the unique tag ID given by the container.

TagData.getAttribute(String attName) returns constant TagData.REQUEST_TIME_VALUE to indicate that the attribute is request time expression and whose value is not available at request time. Note TagExtraInfo class is used only at translation time.

Depending on the variables to be maintained, VariableInfo instances can be created using following constructor

VariableInfo(String varName, String className, boolean declare, int scope)

Just like TLD files, the variable name should be unique and the types can be in short form.

boolean isValid(TagData data)

Helpful in validating attributes of the tag during translation time. Since it can return boolean value only, validate() method is preferred over this.

Some of the containers may not call isValid() method. The default implementation of validate() is to call isValid() and return ValidationMessage indicating failure if the return value of isValid() is false.

ValidationMessage[] validate(TagData data)

Here unlike isValid(), appropriate error messages can be specified. This method should return null or empty array to indicate no errors.

ValidationMessage can be constructed using following constructorValidationMessage(String id, String message)

The id expected by the ValidationMessage is the tag id (container assigns unique id for every tag and can be accessed using TagData instance representing that tag), which is responsible for the

SCWCD Material©2007 IBM Corporation

Page 145: SCWCD 1.4 Material

SCWCD Material 145

error. The id can be null, in which case it is considered to be missing information.

TLD File

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">... ... <tag>

<display-name>var1</display-name> <name>test5</name>

<tag-class>com.test.VarTest</tag-class><body-content>scriptless</body-content>

<tei-class>com.test.VarExtraInfo</tei-class></tag>

</taglib>

SCWCD Material©2007 IBM Corporation

Page 146: SCWCD 1.4 Material

SCWCD Material 146

TagExtraInfo class

public class VarExtraInfo extends TagExtraInfo{

public VariableInfo[] getVariableInfo(TagData data){

System.out.println("getVariableInfo....");VariableInfo info[]=new VariableInfo[2];info[0]=new

VariableInfo("var","java.lang.String",false,VariableInfo.AT_BEGIN);info[1]=new

VariableInfo("othrVar","java.lang.String",false,VariableInfo.AT_BEGIN);

return info;}

public boolean isValid(TagData data){

System.out.println("isValid() method....");return super.isValid(data);

}

public ValidationMessage[] validate(TagData data){

System.out.println("validate() method....");return super.validate(data);

}}

SCWCD Material©2007 IBM Corporation

Page 147: SCWCD 1.4 Material

SCWCD Material 147

Tag Handler Class

public class VarTest extends TagSupport{}

JSP Code

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" isELIgnored="false"%><%@ taglib uri="/tags/test" prefix="tst" %>

<html>

<head><title>Custom Tag Test</title>

</head>

<body><tst:test5/>

<BR><BR><BR><BR>Value of variable var is = <%=var%> and othrVar= <%=othrVar%>

</body></html>

Note: Tomcat 5.5.7 is not working properly with TagExtraInfo class. Generates invalid java file when TagExtraInfo is used.

Communication with the Parent Tags

If a tag is nested tag, the enclosing (or parent) tag instance is passed to the tag using setParent() of both javax.servlet.jsp.tagext.Tag and javax.servlet.jsp.tagext.SimpleTag classes. If the custom classes are extending javax.servlet.jsp.tagext.TagSupport or javax.servlet.jsp.tagext.SimpleTagSupport classes then the immediate enclosing (or parent) tag of the current tag can be accessed using getParent() method. Note for classical methods the type of parent passes is javax.servlet.jsp.tagext.Tag whereas for simple tags the type of parent passed is javax.servlet.jsp.tagext.JspTag.

SCWCD Material©2007 IBM Corporation

Page 148: SCWCD 1.4 Material

SCWCD Material 148

TLD File

<tag><display-name>hier</display-name><name>hier</name><tag-class>com.test.HierarchyTag</tag-class><body-content>scriptless</body-content>

<attribute><name>name</name><required>true</required><type>java.lang.String</type>

</attribute></tag>

Tag Java Source

public class HierarchyTag extends SimpleTagSupport{

private String name;

public void doTag() throws JspException,IOException{

StringBuffer buff=new StringBuffer();buff.append("This tag name is: "+name);

HierarchyTag parent=(HierarchyTag)getParent();while(parent!=null){

buff.append(" ==> ");buff.append(parent.getName());

parent=(HierarchyTag)parent.getParent();}

buff.append("<BR>");getJspContext().getOut().print(buff);

//W/O this stmt nested tags of this tag will not get invokedgetJspBody().invoke(null);

}

public void setName(String name)

SCWCD Material©2007 IBM Corporation

Page 149: SCWCD 1.4 Material

SCWCD Material 149

{this.name=name;

}public String getName(){

return name;}

}

JSP Code

<%@ taglib uri="/tags/test" prefix="tst" %><%@page isELIgnored="false"%>

<html><head>

<title>Simple classic test page</title></head>

<body><tst:hier name="tag1">

<tst:hier name="tag2"><tst:hier name="tag3">

<tst:hier name="tag4"></tst:hier>

</tst:hier></tst:hier>

</tst:hier></body>

</html>

Output

This tag name is: tag1This tag name is: tag2 ==> tag1This tag name is: tag3 ==> tag2 ==> tag1This tag name is: tag4 ==> tag3 ==> tag2 ==> tag1

SCWCD Material©2007 IBM Corporation

Page 150: SCWCD 1.4 Material

SCWCD Material 150

TryCatchFinally interface

This interface (javax.servlet.jsp.tagext.TryCatchFinally) has following two methods. And tags implementing this interface will be served with following additional hooks.

void doCatch(Throwable th)Called if an exception/error occurs during setting attributes or any other life cycle methods of the current tag. This method can throw exception (same or different) which will be propagated.

void doFinally()Called in all the cases even if exception is thrown or not. This will be called even if doCatch() throws exception.

SkipPageException

This exception (javax.servlet.jsp.SkipPageException) is expected to be thrown by SimpleTag or JSPFragment when the rest of the page needs to be skipped. The effect will be similar to the doEndTag() method returning SKIP_PAGE.

SCWCD Material©2007 IBM Corporation

Page 151: SCWCD 1.4 Material

SCWCD Material 151

Tag Files

Tag files are the means by which we can develop reusable presentation logic components. A tag file is a source file that provides a way for a page author to abstract a segment of JSP code and make it reusable via a custom action. Tag files allow a JSP page author to create tag libraries using JSP syntax. The required file extensions for a tag file are .tag or .tagx.

Tag files are converted into “Simple Tag” class file implementations. So all the restrictions of “Simple Tag” will apply to tag files also (like no JSP body-type).

Important points regarding Tag files: Whenever a tag file is invoked a fresh page scope is provided. And the

modifications (in terms of attributes) done to the page scope will not have any effect on the calling page or tag file. This is achieved by using wrapper around JspContext or PageContext passed to Tag file (which in turn can be type cast to JspContext or PageContext respectively).

For every attribute specified in the invoking page tag will be available in the tag file as page-scoped variables. Attributes, which are optional and not specified during invocation, will not be available as variables.

An automatic tag file descriptor corresponding to this tag file is provided by container, which can be accessed from other pages/tag files. Which will be according to tag, attribute and variable attributes.

Just like JSP pages, tag files also can forward/include the request to the other resource. And can use other custom tags in the same way.

Note that tag files are designed to suit for all environments unlike “Classic Tags” which are designed for servlet environment. So it should be remembered that the invocation of “Classic Tag” from tag file may fail in the non-servlet environment (because “Classic Tag” expects PageContext where as non-servlet environment will have only JspContext).

Tag files should be present under /WEB-INF/tags directory of the web application or its sub-directory. No TLD file is needed to use these TAG files as custom actions in JSP or other TAG files.

Tag file code differs from JSP code in following ways: Some directives are not available in TLD files and some have only limited

availability. “page” directive is replaced by “tag” directive. Standard actions <jsp:invoke> & <jsp:doBody> can be used only in tag files.

Packaging of tag files

SCWCD Material©2007 IBM Corporation

Page 152: SCWCD 1.4 Material

SCWCD Material 152

Depending on whether the tag files are application specific or part of reusable components they can be packaged in one of the following ways:

In application’s /WEB-INF/tags directory or one of its subdirectory. This tag file’s location is very useful for application specific ones. Because, these tag files does not need any TLD file. And hence very use to keep reusable JSP fragments and use them as custom tags wherever needed.

In /META-INF/tags directory of JAR files installed in application’s /WEB-INF/lib directory. These files need TLD files otherwise ignored. This procedure is useful for reusable custom tags. Because the packaged JAR file can be deployed in any application and can be reused across applications.

Tag files, which are found under other locations is not considered as tag extensions.

Packaging in a JAR file

As mentioned above when tag files are packed in JAR files (in /META-INF/tags directory), they need TLD file otherwise they will get ignored. Remember, the TLD file need not be provided separately, it can be packed in the same JAR file under /META-INF directory or its sub-directory (and specify its own URI).

In TLD file we can specify about a tag file using <tag-file> element, which in turn comes under <taglib> element. Remember, we can combine classic tags and tag files under single <taglib> element of a TLD file. So the end user can never make out whether the custom action being used is from tag file or from standard java classes.

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">

<display-name>web</display-name><tlib-version>1.0</tlib-version><short-name>jartest</short-name><uri>http://kranthi.com/jartest</uri>

<tag-file><name>tst</name><path>/META-INF/tags/test.tag</path>

</tag-file></taglib>

Packaging Directly in Web application

SCWCD Material©2007 IBM Corporation

Page 153: SCWCD 1.4 Material

SCWCD Material 153

The tag files under application’s /WEB-INF/tags directory goes with application packaging. These files do not need any additional TLD file.

Container treats all the tag files under /WEB-INF/tags and each of its sub-directories as another implicitly defined tag library containing tag handlers defined by tag files under that directory. There is no special relationship between directories they are just meant for organizational purposes only. For example with the following tag file structure in an application

/WEB-INF/tags/a.tag/WEB-INF/tags/b.tag/WEB-INF/tags/foo/c.tag/WEB-INF/tags/bar/baz/d.tag

Container will create 3 TLD files:First one for /Web-INF/tags directory with tag extensions “a” & “b”Second for /WEB-INF/tags/foo/ directory with tag extension “c”Third for /WEB-INF/tags/bar/baz/ directory with tag extension “d”

This implicit TLD files will have following properties: URI is equal to the path of the directory containing the TLD file to be accessed. Short name equal to the directory path excluding /WEB-INF/tags and replacing

“/” with “-“. For example, short name for /WEB-INF/tags/bar/baz/ would “bar-baz”.

For each tag file a <tag-file> element exists with the following properties:o Name: Name of the tag file excluding “.tag” extension.o Path: Relative to the root of the web application.

An implicit TLD can be used in a JSP using “tagdir” attribute of “taglib” directive and this value should start with “/WEB-INF/tags”.

<%@tag import="java.util.*" dynamic-attributes="dynAtt"%><%@attribute name="value" type="java.lang.Integer" required="true" rtexprvalue="true"%>Value specified is ${value}<BR>

SCWCD Material©2007 IBM Corporation

Page 154: SCWCD 1.4 Material

SCWCD Material 154

JSP Code

<%@ taglib tagdir = "/WEB-INF/tags" prefix="tags" %>

<%@page isELIgnored="false"%>

<html><body>

<tags:exp value="10"/></body>

</html>

Despite the existence of the implicit TLD file, explicit reference can be specified in other explicit tag libraries (that is in TLD files) using <tag-file> element.

TLD File

<taglib xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0">… … …

<uri>http://kranthi.com/test</uri><tag>

<display-name>sbdy</display-name><name>sbdy</name><tag-class>com.test.diff.SimpleBodyTag</tag-class><body-content>scriptless</body-content>

</tag>

<tag-file><name>exp</name><path>/WEB-INF/tags/exp.tag</path>

</tag-file>

</taglib>

Packaging as precompiled classes

Tag files can be compiled into tag files using third party tools and can be supplied as JAR files. This can be done when the author wants to distribute binary version of the tag files. But care must be taken that the binary code is portable and uses standard API only.

SCWCD Material©2007 IBM Corporation

Page 155: SCWCD 1.4 Material

SCWCD Material 155

Tag File Directives

Following is the list of directives, which are available in tag files and are similar to that of JSP pages:

taglib include

Following is the list of directives specific to tag files

Directive “tag”

The directive “tag” is similar to “page” directive of JSP pages but this is specific to tag files. Just like “page” directive, “tag” directive can occur any number of times, but two “tag directive” occurrences cannot define different values for the same attribute (but with duplicate values is allowed). “import” and “pageEncoding” are exempt for this rule.

Note: all the attributes are optional.

tag directiveAttribute Name Descriptiondisplay-name A short name that is intended to be displayed by tools. Defaults to the name

of the tag file, without the .tag extension.

body-content Provides information on the content of the body of this tag. Can be either empty, tagdependent, or scriptless (Remember JSP is not allowed because Tag file represents “Simple Tags” not “Classic Tags”. A translation error will result if JSP or any other value is used.

Defaults to scriptless.

dynamic-attributes

If present, the generated tag handler must implement the javax.servlet.jsp.tagext.DynamicAttributes interface, and the container must treat the tag as if its corresponding TLD entry contained <dynamic-attributes>true</dynamic-attributes>.

The value identifies a page scoped attribute in which to place aMap containing the name to value pairs of the dynamic attributes passed during this invocation. Only dynamic attributes with no uri are to be present in the Map; all other dynamic attributes are ignored.

A translation error will result if this name matches with the attribute or variable name defined by “attribute” or “variable” directives (described later).

SCWCD Material©2007 IBM Corporation

Page 156: SCWCD 1.4 Material

SCWCD Material 156

small-icon Either a context-relative path, or a path relative to the tag source file, of an image file containing a small icon that can be used by tools.

large-icon Either a context-relative path, or a path relative to the tag source file, of an image file containing a large icon that can be used by tools.

description Defines an arbitrary string that describes this tag.

example Defines an arbitrary string that presents an informal description of an example of a use of this action.

language Defines scripting language that can be used in scripting elements. Currently only java is available.

import List of packages/classes delimited by comma (,) that needs to be imported. By default following packages/classes are imported into tag file (similar to JSP files):

java.lang.*javax.servlet.*javax.servlet.jsp.* javax.servlet.http.*

pageEncoding Carries the same syntax and semantics of the pageEncoding attribute in the page directive. However, there is no corresponding global configuration element in web.xml.

The pageEncoding attribute cannot be used in tag files in XML syntax.

isELIgnored Carries the same syntax and semantics of the isELIgnored attribute of the page directive. However, there is no corresponding global configuration element in web.xml.

Directive “attribute”

The attribute directive is analogous to the <attribute> element in the Tag Library Descriptor, and allows for the declaration of custom action attributes.

attribute directiveAttribute Name Descriptionname(Mandatory)

Specifies unique name for the attribute.

It is a translation error to have duplicate attribute name or name matching

SCWCD Material©2007 IBM Corporation

Page 157: SCWCD 1.4 Material

SCWCD Material 157

with “dynamic-attributes” value of “tag” directive or name matching with “variable” name.

required Valid values or true or false. Whether this attribute is required or optional.

Default value is false.

fragment Valid values or true or false. Whether this attribute is a fragment.

If true, the type attribute is fixed at javax.servlet.jsp.tagext.JspFragment and a translation error will result if the type attribute is specified.

Also, if this attribute is true, the rtexprvalue attribute is fixed at true and a translation error will result if the rtexprvalue attribute is specified.

Defaults value is false.

rtexprvalue Whether the attribute’s value may be dynamically calculated at runtime by a request-time expression.

Unlike the corresponding TLD element, this attribute defaults value is true.

type The runtime type of the attribute’s value. It is a translation error to specify a primitive type. This restriction is needed because the attribute values passed during tag invocation are accessible in tag file as page-scoped attributes.

Defaults value is java.lang.String

description Description of the attribute. Defaults to no description.

/WEB-INF/tags/exp.tag

<%@tag import="java.util.*" %><%@tag dynamic-attributes="dynAtt"%><%@attribute name="value" type="java.lang.Integer" required="true" rtexprvalue="true"%>

<%-- Accessing attribute value of custom tag--%>Value specified is ${value}<BR><BR>

<B><U>Dynamic Attributes</U></B><BR>

SCWCD Material©2007 IBM Corporation

Page 158: SCWCD 1.4 Material

SCWCD Material 158

<%-- Accessing dynamic attribute mapNote: Scriptlet elements can be used in Tag files just like JSP files

--%><%

Map dynMap= (Map)jspContext.getAttribute("dynAtt",javax.servlet.jsp.PageContext.PAGE_SCOPE);

Iterator it=dynMap.keySet().iterator();

Object key=null;Object value=null;

while(it.hasNext()){

key=it.next();value=dynMap.get(key);

%><%=key %>: <%=value %><BR>

<%}

%>

JSP File

<%@ taglib tagdir="/WEB-INF/tags" prefix="tst" %><%@page isELIgnored="false"%>

<html><body>

<tst:exp value="10" att1="2334" att2="test" att3="value"></tst:exp></body>

</html>

Directive “variable”

The variable directive is analogous to the <variable> element in the Tag Library descriptor, and defines the details of a variable exposed by the tag handler to the calling page.

variable directiveAttribute Name Descriptionname-given Defines the name of the variable. Its translation error to specify duplicate

variable name or name matching with any of this tag attribute or name matching with “dynamic-attributes” value of “tag” directive.

SCWCD Material©2007 IBM Corporation

Page 159: SCWCD 1.4 Material

SCWCD Material 159

Either the name-given attribute or the name-from-attribute attribute must be specified.

name-from-attribute

The specified name is the name of an attribute whose (translation-time) value at of the start of the tag invocation will give the name of the variable.

A translation error will result if there is no attribute is found with following conditions

Name equal to this attribute value Type java.lang.String Should be mandatory Should not be rtexprvalue.

Either the name-given attribute or the name-fromattribute attribute must be specified.

A translation error will result if two variable directives have the same namefrom-attribute.

alias Defines a locally scoped attribute to hold the value of this variable. The container will synchronize this value with the variable whose name is given in name-from-attribute.

Required when name-from-attribute is specified. A translation error must occur if used without name-fromattribute.

A translation error must occur if the value of alias is the same as any attribute name or the “name-given” attribute of a variable directive in the same translation unit.

variable-class Defines type of variable.

The default is java.lang.String.

declare Whether the variable is declared or not in the calling page/tag file, after this tag invocation.

Default value is true.

scope The scope of the scripting variable defined. Can be either AT_BEGIN, AT_END, or NESTED.

Default value is NESTED.

description An optional description of this variable.

SCWCD Material©2007 IBM Corporation

Page 160: SCWCD 1.4 Material

SCWCD Material 160

/WEB-INF/tags/exp.tag

<%@tag import="java.util.*" %><%@tag dynamic-attributes="dynAtt"%>

<%-- Declaring a variable--%><%@variable name-given="var1" scope="AT_BEGIN"%>

<%-- Assiging value for variable --%><%

jspContext.setAttribute("var1","Simple Value");%>

JSP File

<%@ taglib tagdir="/WEB-INF/tags" prefix="tst" %><%@page isELIgnored="false"%>

<html><body>

<tst:exp/>Variable value: <%=var1%>

</body></html>

Implicit objects

Implicit objects available in tag files differs from JSP pages in following ways: pageContext is replaced with jspContext. Implicit objects page & exception are not available.

Following table lists all the implicit objects available for tag files:

Implicit Object Name

Description

SCWCD Material©2007 IBM Corporation

Page 161: SCWCD 1.4 Material

SCWCD Material 161

request Type: Depending on protocol it can be javax.servlet.ServletRequest or its subclass (Eg, javax.servlet.http.HttpServletRequest)

Represents the request object. Can be used to access request scope attributes.response Type: Depending on protocol it can be javax.servlet.ServletResponse or its

subclass (Eg, javax.servlet.http.HttpServletResponse)

Represents response object of the page.jspContext Type: javax.servlet.jsp.JspContext

Jsp context for this tag file. This will be instance of PageContext in servlet environment.

session Type: javax.servlet.http.HttpSession

This variable is valid only for HTTP protocol.

Represents current user session. Can be used to access session scope attributes.

application Type: javax.servlet.ServletContext

Current application context and used to access application scope attributes.out Type: javax.servlet.jsp.JspWriter

Represents response output stream.config Type: javax.servlet.ServletConfig

ServletConfig of the current page.

Tag file specific Standard actions

Following are the list of standard actions specific to Tag files and not to JSP files.

Action <jsp:invoke>

SCWCD Material©2007 IBM Corporation

Page 162: SCWCD 1.4 Material

SCWCD Material 162

This action invokes the “JSP fragment attribute” specified using “fragment” attribute. The output of the fragment can be sent to current JspWriter or to the scoped attribute for further evaluation.

If specified fragment is null, this action behaves as though the specified fragment result in no output.

Attributes of <jsp:invoke>Attribute Name Descriptionfragment(Mandatory)

Name of the fragment attribute of the current custom tag invocation.

var The scoped attribute name where the result of the fragment should be stored as String object.

A translation error must occur if both var and varReader are specified.

If neither var nor varReader are specified, the result of the fragment goes directly to the current JspWriter.

varReader The scoped attribute name where the result of the fragment should be stored as Reader object. This reader is resetable, that is reset() call on this reader will allow to read the content from starting without re-invocation of the fragment.

A translation error must occur if both var and varReader are specified.

If neither var nor varReader are specified, the result of the fragment goes directly to the current JspWriter.

scope The scope in which to store the resulting variable.

A translation error must result if the value is not one of page, request, session, or application.

A translation error will result if this attribute appears without specifying either the var or varReader attribute as well.

Note that a value of session should be used with caution since not all calling pages may be participating in a session.

Default value is “page”.

SCWCD Material©2007 IBM Corporation

Page 163: SCWCD 1.4 Material

SCWCD Material 163

/WEB-INF/tags/exp.tag

<%@tag import="java.util.*" %><%@tag dynamic-attributes="dynAtt"%>

<%-- Declaring JSP Fragment attribute --%><%@attribute name="content" fragment="true" required="true"%>

<%@attribute name="count" type="java.lang.Integer" required="true"%>

<%int count= ((Integer)jspContext.getAttribute("count")).intValue();

for(int i=0;i<count;i++){

%><%-- Example of invoking JSP Fragment attribute

Here the JSP fragment attribute is "content"--%><jsp:invoke fragment="content"/>

<%}

%>

JSP File

<%@ taglib tagdir="/WEB-INF/tags" prefix="tst" %><%@page isELIgnored="false"%>

<html><body>

<tst:exp count="3"><jsp:attribute name="content">

<jsp:text>This is simple jsp fragment.</jsp:text><BR></jsp:attribute>

</tst:exp></body>

</html>

Action <jsp:doBody>

SCWCD Material©2007 IBM Corporation

Page 164: SCWCD 1.4 Material

SCWCD Material 164

<jsp:doBody> is similar to the <jsp:fragment> with the only difference that instead of invoking a fragment attribute, this action will invoke the current custom tag body.

Attributes of <jsp:doBody>Attribute Name Description

var The scoped attribute name where the result of the fragment should be stored as String object.

A translation error must occur if both var and varReader are specified.

If neither var nor varReader are specified, the result of the fragment goes directly to the current JspWriter.

varReader The scoped attribute name where the result of the fragment should be stored as Reader object. This reader is resetable, that is reset() call on this reader will allow to read the content from starting without re-invocation of the fragment.

A translation error must occur if both var and varReader are specified.

If neither var nor varReader are specified, the result of the fragment goes directly to the current JspWriter.

scope The scope in which to store the resulting variable.

A translation error must result if the value is not one of page, request, session, or application.

A translation error will result if this attribute appears without specifying either the var or varReader attribute as well.

Note that a value of session should be used with caution since not all calling pages may be participating in a session.

Default value is “page”.

SCWCD Material©2007 IBM Corporation

Page 165: SCWCD 1.4 Material

SCWCD Material 165

/WEB-INF/tags/exp.tag

<%@tag import="java.util.*" %>

<%-- By default body-content type is "scriptless" --%><%@tag dynamic-attributes="dynAtt"%>

<%@attribute name="count" type="java.lang.Integer" required="true"%>

<%int count= ((Integer)jspContext.getAttribute("count")).intValue();

for(int i=0;i<count;i++){

%><%-- Example of invoking Custom Tag body --%><jsp:doBody/>

<%}

%>

JSP File

<%@ taglib tagdir="/WEB-INF/tags" prefix="tst" %><%@page isELIgnored="false"%>

<html><body>

<tst:exp count="3"><jsp:body>

<jsp:text>This is simple jsp fragment body.</jsp:text><BR></jsp:body>

</tst:exp></body>

</html>

SCWCD Material©2007 IBM Corporation

Page 166: SCWCD 1.4 Material

SCWCD Material 166

TLD File Structure

In the following diagrams:* Indicates one or more occurrence of current element+ One or more occurrence of current element? Zero or one occurrence of current element

SCWCD Material©2007 IBM Corporation

Page 167: SCWCD 1.4 Material

SCWCD Material 167

SCWCD Material©2007 IBM Corporation

Page 168: SCWCD 1.4 Material

SCWCD Material 168

SCWCD Material©2007 IBM Corporation

Page 169: SCWCD 1.4 Material

SCWCD Material 169

JSP Documents

JSP documents are nothing but JSP in name-space aware XML syntax. Following are the advantages of JSP documents:

The content can be generated in the most standard format, XML for example XHTML, SVG, WML, etc.

The generated XML content can be easily manipulated/processed by XML aware tools.

Tools using XML Object serialization can easily generate a JSP document.

Following table shows the mapping JSP pages to JSP documents

Element Type JSP Page JSP DocumentDirectives <%@page

import”java.util.*”%><jsp:directive.page import=”java.util.*”>

Declaration <%! int i=1; %> <jsp:declaration> int i=1; </jsp:declaration>

Scriptlet <% list.add(“val”); %> <jsp:scriptlet> list.add(val);</jsp:scriptlet>

Text Simple text <jsp:text>Simple text</jsp:text>Expression <%=i%> <jsp:expression>i

</jsp:expression>

A file is identified to be a JSP document in one of the following case: By configuring web.xml using element <is-xml> under <jsp-property-group>

element.

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.4">

<display-name>Custom Tags</display-name><jsp-config>

<jsp-property-group><url-pattern>*.svg</url-pattern><is-xml>true</is-xml>

</jsp-property-group></jsp-config>

</web-app>

SCWCD Material©2007 IBM Corporation

Page 170: SCWCD 1.4 Material

SCWCD Material 170

If the web.xml uses 2.4 version and the extension of the file is “.jspx”. If the file is explicitly or implicitly identified as JSP page and the root element is

<jsp:root>. This is useful for JSP 1.2 backward compatibility.

Note its translation time for a file which is identified as JSP document is not well-formed or not name-space aware.

Note till JSP 1.2 it was mandatory to have <jsp:root> as JSP document root element. From JSP 2.0 it’s not mandatory.

All the standard and custom actions are identified by the container by the URI (in the taglib element) corresponding to the prefix used for the action element. The URI for standard actions of JSP is “http://java.sun.com/JSP/Page”.

<html xmlns:tst="http://kranthi.com/test" xmlns:jsp="http://java.sun.com/JSP/Page"><body>

<tst:test strVal="simpleVale"/><BR/><BR/><jsp:text>Simple text for testing</jsp:text>

</body></html>

During conversion of JSP documents all the white spaces are discarded (as per the XSLT specification). Only exception is the text that appears in <jsp:text>.

If a DOCTYPE element is specified in JSP document, then container should validate the JSP XML document as per the specified DTD. And the errors will be treated as any other translation error. JSP 2.0 does not support schema validation.Following are the important points to be noted regarding JSP documents:

The resultant content of the JSP document by default is set to be of XML content (In generated class file using response.setContentType("text/xml;charset=UTF-8")). So in order to display content as HTML the content-type header has to be set explicitly (For example, using explicit response.setContentType()).

White spaces in JSP documents are discarded at translation time. So the white spaces generated by custom/standard actions will not be truncated.

Standard JSP comments cannot be used in JSP documents. Instead use XML comments. And unlike JSP pages, XML comments specified in JSP documents will not be part of resultant content.

XML comments cannot be used in scripting based action elements. Instead use java comments.

JSP documents also contains following implicit imports (just like JSP pages)o javax.servlet.*o javax.servlet.http.*

SCWCD Material©2007 IBM Corporation

Page 171: SCWCD 1.4 Material

SCWCD Material 171

o javax.servlet.jsp.*

Expressions

Standard expression element <%=expr%> is used in different syntax in JSP documents. The syntax looks like

%=expr%

Notice the missing “<” and “>”. In JSP documents this expression syntax can be used only in custom action attributes not in template text.

In order to have EL expressions as template text simply use “\” before EL expressions (just like in JSP pages). Note in template text “\” will not act as escape character other than for EL expressions. But when used attribute values, “\” acts as escape character for all java standard escapable chars and also for EL expressions. Note even in attribute values “\” itself does not need escape character by itself.

\${expr} will result in ${expr}\\${expr} will result in \${expr}

EL expression can be used in any place- custom/standard actions and in template text also.

<html xmlns:tst="http://kranthi.com/test" xmlns:jsp="http://java.sun.com/JSP/Page"><jsp:directive.page import="com.test.beans.*"/>

<jsp:scriptlet>int val=100;request.setAttribute("emp",new Employee("test",new Address(),10,34543));request.setAttribute("val",new Integer(val));

/* Set response content type. By default result content is treated asXML content */response.setContentType("text/html");

</jsp:scriptlet>

<body><!-- Expression/EL Expression usage in custom actions --><tst:test intVal="%=val%"/><tst:test intVal="${val}"/>

SCWCD Material©2007 IBM Corporation

Page 172: SCWCD 1.4 Material

SCWCD Material 172

<!-- Expression/EL Expression usage in standard actions --><jsp:setProperty name="emp" property="age" value="%=val%"/>Age= <jsp:getProperty name="emp" property="age"/>

<jsp:setProperty name="emp" property="age" value="${val}"/>Age= <jsp:getProperty name="emp" property="age"/>

<BR/><BR/><!--NOTE: Expressions are not evaluated in template text

The result of below text will be "Simple text for testing with value %=val%"

-->Simple text for testing with value %=val%<BR/>

<!-- EL expressions are evaluated in template text alsoResult of blow statement is

"Simple text for testing with value 100"-->Simple text for testing with value ${val}

</body></html>

Directive Standard Actions

In JSP documents due to XML syntax, directives cannot be used in their standard format. Hence, additional standard actions are defined to support directive elements in JSP documents.

Action <jsp:directive.page>

Action <jsp:directive.page> represents “page” directive in JSP document and holds the same attribute list and conditions as <%@page %> in JSP.

Syntax: <jsp:directive.page page_directive_attr_list />

Action <jsp:directive.include>

Action <jsp:directive.page> represents “include” directive in JSP document and holds the same attribute list and conditions as <%@include %> in JSP.

Syntax: <jsp:directive.include file="relativeURLspec” />

NOTE: Equivalent <%@taglib%> is not present because in place of that name-space is used directly.

SCWCD Material©2007 IBM Corporation

Page 173: SCWCD 1.4 Material

SCWCD Material 173

Scripting Element Standard Actions

In JSP documents due to XML syntax, scripting elements (declarations, scriptlets and expressions) cannot be used in their standard format. Hence, additional standard actions are defined to support directive elements in JSP documents.

Action <jsp:declaration>

This is replacement for <%! Declarations %> of JSP in JSP documents.

Syntax: <jsp:declaration> declaration goes here </jsp:declaration>

Action <jsp:scriptlet>

This is replacement for <% Scriptlet %> of JSP in JSP documents.

Syntax: <jsp:scriptlet> code fragment goes here </jsp:scriptlet>

Action <jsp:expression>

This is replacement for <%= Expression %> of JSP in JSP documents.

Syntax: <jsp:expression> expression goes here </jsp:expression>

Other Standard Actions

All the standard actions that can be used JSP pages can also be used in JSP documents.

Action <jsp:root>

<jsp:root> can appear only in JSP documents and that to as a root element only. In JSP 1.2 its mandatory to have <jsp:root> as root element in JSP & tag documents. But from JSP 2.0 its not mandatory to have <jsp:root> as root element.

<jsp:root> is having following two advantages: To indicate current file as JSP document without using any configuration and

without having .jspx extension. To accommodate content which cannot be represented as a single XML

document. Consider following example

SCWCD Material©2007 IBM Corporation

Page 174: SCWCD 1.4 Material

SCWCD Material 174

<jsp:root xmlns:jsp=”http://java.sun.com/JSP/Page” version=”2.0"> <table>foo</table> <table>bar</table></jsp:root>

It can also be used to define namespaces for standard and custom actions.

When <jsp:root> is used, container will not insert XML declaration. This behavior can be changed by using <jsp:output> element.

<jsp:root xmlns:jsp=”http://java.sun.com/JSP/Page” version=”2.0"><jsp:output omit-xml-declaration="no"/><table>foo</table>

</jsp:root>

Attributes of <jsp:root>Attribute Name Descriptionversion(Mandatory)

The version of the JSP specification used in this page. Valid values are "1.2" and "2.0". It is a translation error if the container does not support the specified version.

Action <jsp:output>

Action <jsp:output> is used for two purposes: To add/remove <?xml> declaration in the output. To generate <!DOCTYPE> element in the output.

Its illegal to have multiple occurrences of <jsp:output> with different attribute values.

Attributes of <jsp:output>Attribute Name Descriptionomit-xml-declaration

Indicates whether to omit the generation of an XML declaration. Acceptable values are “true”, “yes”, “false” and “no”.

Even if <?xml> declaration appears statically (explicitly specified) it will be removed, if this attribute value is true/yes.

The default value for JSP documents with <jsp:root> element is “yes” otherwise “no”.

SCWCD Material©2007 IBM Corporation

Page 175: SCWCD 1.4 Material

SCWCD Material 175

The default value for tag file is always “yes”.

doctype-system Specifies that a DOCTYPE declaration is to be generated and gives the value for the System Literal.

doctype-root-element

Indicates the name that is to be output in the generated DOCTYPE declaration.

Must be specified if and only if doctype-system is specified.

This value should match with the root element of output XML otherwise as per XML standards DTD validation will not be applied. Anyhow container will not raise any error.

doctype-public Gives the value for the Public ID for the generated DOCTYPE.

Must be specified if and only if doctype-system is specified.

Example# 1

<jsp:output doctype-root-element=”html” doctype-public=”-//W3C//DTD XHTML Basic 1.0//EN” doctype-system=”http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd” />

Output<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML Basic 1.0//EN”

“http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd”>

Example# 2

<jsp:output omit-xml-declaration=”true” doctype-root-element=”elementA” doctype-system=”test.dtd” />

Output<!DOCTYPE elementA SYSTEM “test.dtd”>

SCWCD Material©2007 IBM Corporation

Page 176: SCWCD 1.4 Material

SCWCD Material 176

Core JSTL (Java Standard Tag Library)

We include the JSTL core library with the following tag-lib declaration

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

In the following sections we use prefic “c” for all actions which represnts URI “http://java.sun.com/jsp/jstl/core”

Action <c:set>

Action <c:set> can be used for two purposes For setting scoped attributes

Specifying value using “value” attribute<c:set value=”value” var=”varName”

scope=”{page|request|session|application}”]/>

Specifying value using body-content<c:set var=”varName” [scope=”{page|request|session|application}”]>

body content</c:set>

For setting property for the target bean or java.util.Map

Specifying value using “value” attribute<c:set value=”value” target=”target” property=”propertyName”/>

Specifying value using body-content<c:set target=”target” property=”propertyName”>

body content</c:set>

SCWCD Material©2007 IBM Corporation

Page 177: SCWCD 1.4 Material

SCWCD Material 177

Attributes of action <c:set>Name Request Time

ExpressionType Description

var False String Names of the scoped attribute.

If “var” is specified, “target” & “property” are ignored.

“var” is mandatory if “target” is not specified.value True Object Expression to be evaluated.

If value is not specified (both in “value” and body) an empty string is assumed.

If the value is null Scoped attributed will be removed Or if target is Map, the entry will get

removed. Or if the target is Bean, then the property

is set to null.

scope False String Scope of var. (page|request|session|application)

Default is “page”.

target True Object Should be a java bean whose property needs to be set. Or it should be java.util.Map

Exception will be thrown if this evaluates to be null.

“target” is mandatory if “var” is not specified.

property True String Name of the property to be set in the “target” object/Map.

If “property” value is not specified: If the target is “map”, then an entry with

value as specified value and null as key will get added.

If the target is “Object”, then an exception is thrown saying “Invalid property: null”.

SCWCD Material©2007 IBM Corporation

Page 178: SCWCD 1.4 Material

SCWCD Material 178

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html>

<body bgcolor="#FFFFFF"><c:set var="testVar" value="<%="100"%>"/>Value of test variable is ${testVar}.

<c:set var="testVar">100</c:set></body>

</html>

<%HashMap map=new HashMap();String value="Simple Value";

%><html>

<body bgcolor="#FFFFFF"><c:set value="<%=value%>" target="<%=map%>"/>

</body></html>

Action <c:remove>

Removes the specified scoped variable.

Attributes of action <c:remove>Name Request Time

ExpressionType Description

var(Mandatory)

False String Names of the scoped attribute.

scope False String Scope of var.

If specified, removes specified scoped-attribute from specified scope (calls PageContext.removeAttribute(varName, scope)).

If not specified, removes the specified attribute

SCWCD Material©2007 IBM Corporation

Page 179: SCWCD 1.4 Material

SCWCD Material 179

from all scopes (calls PageContext.removeAttribute(varName)) .

<c:set var="testVar" value="110" scope="page"/><c:set var="testVar" value="200" scope="request"/><c:set var="testVar" value="300" scope="application"/>

<%--Displays "110" (from page scope).--%>Value of test variable is ${testVar}.<BR>

<c:remove var="testVar" scope="page"/>

<%-- Displays "200" (from request scope).--%>Value of test variable is ${testVar}.<BR>

<c:set var="testVar" value="110" scope="page"/><c:remove var="testVar"/>

<%-- Displays "" ("testVar" will not be found).--%>Value of test variable is ${testVar}.

Action <c:out>

Evaluates specified expression and outputs the result to the current JSPWriter.

Syntaxes:Without a body

<c:out value=”value” [escapeXml=”{true|false}”] default=”defaultValue”] />

With a body<c:out value=”value” [escapeXml=”{true|false}”]>

default value</c:out>

Attributes of action <c:out>Name Request Time

ExpressionType Description

value True Object Expression to be evaluated

SCWCD Material©2007 IBM Corporation

Page 180: SCWCD 1.4 Material

SCWCD Material 180

(Mandatory) If this value evaluates to be java.io.Reader, then

the data will be read from reader and then is outputted to the current JSPWritter.

escapeXml True boolean If this value is true, XML standard character in the result will get encoded as per XML specification (see table below).

Default value is true.default True Object This value will be used if the “value” gets

evaluated to be null.

Default value can be specified with this attribute or it can also be specified as body content. (See the syntax below).

Character Character Entity Code< &lt;> &gt;& &amp;‘ &#039;“ &#034;

<c:set var="testVar" value="\'Kranthi\'" scope="page"/>

<%-- Generates output &#039;Kranthi&#039; (in HTML source)

--%><c:out value="${testVar}"/><BR>

<%-- Generates output 'Kranthi' (in HTML source)

--%><c:out value="${testVar}" escapeXml="false"/>

Action <c:catch>

SCWCD Material©2007 IBM Corporation

Page 181: SCWCD 1.4 Material

SCWCD Material 181

This action is similar to try-catch block of Java. This is used to catch java.lang.Throwable objects that might be thrown by the nested actions.

Generally this should be used to enclose actions/code, which is of secondary importance. For primary importance, the general behavior expected is to redirect the user to error page.

Attributes of action <c:catch>Name Request Time

ExpressionType Description

var False String If this value is specified, then the Throwable object thrown in the nested code (if any) will be stored in the page scope with this (the specified value) attribute name.

If no exception/error is thrown, then if a scoped attribute (page scoped) exists, then it will get removed (only from page scope).

<c:set var="ex" value="No Exception (page)" scope="page"/><c:set var="ex" value="No Exception (request)" scope="request"/>

<c:catch var="ex"><%

if(1==1)throw new NullPointerException("Exception for testing");

%></c:catch>

<%-- Prints "java.lang.NullPointerException: Exception for testing"--%>Exception caught is: <c:out value="${ex}"/><BR>

<c:catch var="ex"/>

<%--Prints "No Exception (request)"--%>Exception caught is: <c:out value="${ex}"/>

Action <c:if>

SCWCD Material©2007 IBM Corporation

Page 182: SCWCD 1.4 Material

SCWCD Material 182

This action is similar to the “if” condition of Java language. The nested actions/code/body will be evaluated only if the specified expression evaluates to be “true”.

Attributes of action <c:if>Name Request Time

ExpressionType Description

test(Mandatory)

True boolean If this value is true, then only the body content will be evaluated.

var False String Name of the scoped variable, which will be used to store the result of the “test” attribute evaluation.

This variable type will be Boolean.scope False String Scope of the var

This attribute can be specified only if “var” is specified.

<c:set var="val" value="100" scope="page"/>

<c:if test="${val eq 100}" var="result">If condition is successful.<BR>

</c:if>

<%-- Prints as "true" --%>Result is: ${result}

Actions <c:choose>, <c:when> & <c:otherwise>

These actions resemble switch-case-default statements of Java language. These actions can be used where “if- else if- else” conditional logics needs to be specified.

Body content of <c:choose> action One or more <c:when> conditions as immediate child actions. In <c:choose> its

mandatory to have at least one <c:when> as child element. Zero or one <c:otherwise> action. Action <c:otherwise> should be the last the

child action of <c:choose>. After <c:otherwise> no <c:when> action should be specified.

SCWCD Material©2007 IBM Corporation

Page 183: SCWCD 1.4 Material

SCWCD Material 183

<c:choose> body can not contain any thing other than <c:when> and <c:otherwise>. Not even static text.

<c:choose> will evaluate the body of the first <c:when> action whose test condition gets evaluated to true. If none of the <c:when> test conditions get evaluated to true, then <c:otherwise> will get evaluated. Note as a final result only one nested action of <c:choose> will get evaluated.

<c:choose> & <c:otherwise> does not have any attributes.

Attributes of action <c:when>Name Request Time

ExpressionType Description

test(Mandatory)

True boolean If this value is true, then only the body content will be evaluated/processed.

<c:set var="val" value="100" scope="page"/><c:choose>

<c:when test="${val == 110}">Val is 100

</c:when>

<c:when test="${val eq 200}">Val is 200

</c:when>

<c:otherwise>Otherwise got executed.

</c:otherwise></c:choose>

JSTL Iterator Actions

Action <c:forEach>

SCWCD Material©2007 IBM Corporation

Page 184: SCWCD 1.4 Material

SCWCD Material 184

Repeats the nested body content over the collection/array of objects or for specified number of times. Following is the list of supported types through which this action can iterate:

All type of collections (java.util.List & java.util.Set): Iterator object obtained by getIterator() is used to iterate through the collection.

Maps (java.util.Map): To iterate through the Map entrySet().iterator() is used. And the current object type will be java.util.Map.EntrySet which has properties like getKey() and getValue().

All type of arrays (including primitives): For primitive arrays the current object will be appropriate wrapper object.

Iterator/Enumeration: When using this it is important to remember that these objects can be used only once.

String: Iterates through the obtained tokens out of tokenizing the specified String using comma (,) as delimiter. But this is deprecated functionality.

Attributes of action <c:forEach>Name Request Time

ExpressionType Description

var False String Name of the current item in the iteration.

This variable has nested scope visibility.

items True Types specified above.

Items to iterate over.

If this value is specified and is null, then iteration will not take place.

If not specified, then “begin” and “end” are mandatory.

varStatus False String Name of variable which indicates the current iteration/var status.

This will be of type javax.servlet.jsp.jstl.core.LoopTagStatus.

This variable has nested scope visibility.

begin True int If “items” is specified, the iteration starts from item present at this “begin” index.

SCWCD Material©2007 IBM Corporation

Page 185: SCWCD 1.4 Material

SCWCD Material 185

If “items” is not specified, iteration starts with this value.

If specified, this value should be >=0.

If “items” is not specified, then “begin” and “end” are mandatory.

If “items” is specified and “begin” is not specified, iteration starts from 0 (zero).

end True int If “items” is specified, the iteration stops at item present at this “end” index (this index inclusive).

If “items” is not specified, iteration stops when iteration count is equal to this value.

If (end < begin) then no iteration will occur.

If “items” is not specified, then “begin” and “end” are mandatory.

If “items” is specified and “end” is not specified, then iteration continues till the end of the items.

step True int The incrementing value for each iteration.

If specified step >= 1.

Properties of class “ javax.servlet.jsp.jstl.core.LoopTagStatus ”

Property (Type) Descriptionbegin (Integer) Specified begin value. If not specified this will return null.end (Integer) Specified end value. If not specified this will return null.step (Integer) Specified step value. If not specified this will return null.current (Object) Returns the current collection item.index (int) Returns the current index. Note the index value increments by specified

step value in every iteration.first (boolean) True, if the current iteration is first iteration. This need not mean index

value is 0 (actually it will be equal to “begin” value). last (boolean) True if the current iteration is going to be the last iteration.count (int) Returns the iteration count. Note this value will return actual iteration

count not index and starts with 1.

SCWCD Material©2007 IBM Corporation

Page 186: SCWCD 1.4 Material

SCWCD Material 186

<%int arr[]={0,5,10,15,20,25,30,35,40};HashMap map=new HashMap();

for(int i=0;i<10;i++)map.put("k"+i,"v"+i);

%><html>

<body bgcolor="#FFFFFF"><%-- Output:

1 - Simple text2 - Simple text....

--%><c:forEach var="i" begin="1" end="5">

${i} - Simple text<BR></c:forEach><BR><BR>Next Loop<BR>

<%-- Output: (Note the items will be in order returned by Map iterator)Key: k3 Value: v3Key: k6 Value: v6Key: k1 Value: v1

--%><c:forEach var="entry" items="<%=map%>" begin="2" end="4">

Key: ${entry.key} Value: ${entry.value}<BR></c:forEach><BR><BR>Next Loop<BR>

<%--Output:Index: 2 Count: 1 Value: 10Index: 4 Count: 2 Value: 20Index: 6 Count: 3 Value: 30

--%><c:forEach var="val" varStatus="stat" items="<%=arr%>" begin="2"

end="7" step="2">Index: ${stat.index} Count: ${stat.count} Value: ${val}<BR>

</c:forEach></body>

</html>

SCWCD Material©2007 IBM Corporation

Page 187: SCWCD 1.4 Material

SCWCD Material 187

Action <c:forTokens>

Iterates the nested body, for each token of specified string separated by specified delimiters.

Attributes of action <c:forEach>Name Request Time

ExpressionType Description

var False String Name of the current token in the iteration.

This variable has nested scope visibility.items(Mandatory)

True String String which needs to be tokenized.

delims(Mandatory)

True String The set of delimiters as string.

If this value is null, then the “items” (source string) is treated as single token.

varstatus False String Name of variable which indicates the current iteration/var status.

This will be of type javax.servlet.jsp.jstl.core.LoopTagStatus.

This variable has nested scope visibility.begin True int If “items” is specified, the iteration starts from

item present at this “begin” index.

If “items” is not specified, iteration starts with this value.

If specified, this value should be >=0. Default value is zero.

end True int If “items” is specified, the iteration stops at item present at this “end” index (this index inclusive).

If “items” is not specified, iteration stops at this value.

If (end < begin) then no iteration will occur.step True int The incrementing value for each iteration.

If specified step >= 1.

SCWCD Material©2007 IBM Corporation

Page 188: SCWCD 1.4 Material

SCWCD Material 188

<%--Output:Value: val0Value: val2Value: val4

--%><c:forTokens var="val" items="val0,val1,val2,val3,val4,val5,val6" delims="," end="5" step="2">

Value: ${val}<BR></c:forTokens>

JSTL URL Related Actions

Action <c:import>

Imports specified resource data from specified URL.

Syntax#1: In this case the imported data will be written to “out” object.

<c:import url=”url” [context=”context”][var=”varName”] [scope=”{page|request|session|application}”][charEncoding=”charEncoding”]>

optional body content for <c:param> subtags</c:import>

Syntax#2: Resource content is exported as Reader object and is placed in the specified scoped attribute.

<c:import url=”url” [context=”context”] varReader=”varReaderName”[charEncoding=”charEncoding”]>

body content where varReader is consumed by another action</c:import>

Attributes of action <c:import>Name Request Time

ExpressionType Description

url(Mandatory)

True String The URL of the resource to import.

If null/empty/invalid then exception is thrown.

If the url is not fully specified (www.google.com instead of http://www.google.com) or if it not

SCWCD Material©2007 IBM Corporation

Page 189: SCWCD 1.4 Material

SCWCD Material 189

starting with “/” (context relative) then it is considered as relative url.

Note if the url starts with “/” it is treated as context-relative and (“/” + <context name>) will get prepended to specified url.

context True String Name of context (in same container) to which the specified URL belongs.

If specified, the context name and URL should start with “/”.

var False String If specified, the imported content will be stored as String object as scoped attribute with name specified in this “var” attribute.

If “var” is specified then “varReader” should not be specified.

scope False String Scope of the “var”.charEncoding

False String Character encoding of the content at the input resource.

varReader False String Name of the exported scoped variable for the resource content. The type of this variable is Reader.

This is a nested scope variable.

If “var” is specified then “varReader” should not be specified.

This action can have body only when “varReader” is specified.

Notes:

1. Its illegal to use <c;param> in second syntax (when varReader is specified).2. It is illegal to specify both “var” and “varReader”.3. When context name is specified, the URL should be relative URL (starting with

“/”).4. The parameters specified using <c:param> will take precedence over the existing

request parameters.5. For including resource with relative path (same context or other context), request

dispatcher will be used. Where as for absolute URL, java.net.URL will be used. When including other resource using HTTP, GET method will be used.

6. <c:import> can have only if “varReader” is specified. And body can have any JSP content.

SCWCD Material©2007 IBM Corporation

Page 190: SCWCD 1.4 Material

SCWCD Material 190

<c:import url="http://www.google.com"/><c:import url="http://www.google.com" varReader="reader">

<c:out value="${reader}" escapeXml="false"/></c:import>

Action <c:url>

Builds the URL with proper encoded parameters (if any). This action may rewrite local URLs (non-absolute URL) to include session tracking. Absolute URLs are not written in this matter for the sake of security (the session-ID may be exposed to outside world).

This action may contain <c:param> tags inside its body which will be sent as request parameters to the destination URL. This parameters will get properly encoded automatically.

Attributes of action <c:url>Name Request Time

ExpressionType Description

value(Mandatory at run time)

True String URL to be processed. The sepecified URL will not get encoded.

URL can be absolute (http://google.com) or context based and relative.

context True String Name of context (in same container) to which the specified URL belongs.

If specified, the context name and URL should start with “/”.

var False String Name of the scoped attribute where the built URL should be stored.

If not specified the resultant URL will get written to current JspWritter.

scope False String Scope of var.

Important Points: URL specified in “value” will not get encoded. The parameter(s) specified using

<c:param> gets encoded. Body of <c:url> action other than <c:param> actions will be simply ignored.

SCWCD Material©2007 IBM Corporation

Page 191: SCWCD 1.4 Material

SCWCD Material 191

<%--Output (the url specified in "value" is not encoded):http://google.com?search=1+srch+str&search2=2+srch+str&var= simple var

Note: Body other than <c:param> is ignored.--%>Absolute URL:

<c:url value="http://google.com?var= simple var"><c:param name="search" value="1 srch str"/>dfsd<c:param name="search2" value="2 srch str"/>

</c:url>

<%--Output (Note /cust is context root): /cust/ctest.jsp?search=1+srch+str&search2=2+srch+str&var= simple var

--%><BR>Context Relative URL:

<c:url value="/ctest.jsp?var= simple var"><c:param name="search" value="1 srch str"/>dfsd<c:param name="search2" value="2 srch str"/>

</c:url>

<%--Output: ctest.jsp?search=1+srch+str&search2=2+srch+str&var= simple var

--%><BR>Relative URL:

<c:url value="ctest.jsp?var= simple var"><c:param name="search" value="1 srch str"/>dfsd<c:param name="search2" value="2 srch str"/>

</c:url>

Action <c:redirect>

Sends a HTTP redirect to the client with the specified URL. This action can contain <c:param> tags in its body. All the body content, other than <c:param> actions will get ignored.

Attributes of action <c:redirect>Name Request Time

ExpressionType Description

url True String The URL of the resource to redirect to.

SCWCD Material©2007 IBM Corporation

Page 192: SCWCD 1.4 Material

SCWCD Material 192

context True String Name of context (in same container) to which the specified URL belongs.

If specified, the context name and URL should start with “/”.

<c:redirect url="http://google.com"/>

Action <c:param>

Used to specify parameters in <c:import>, <c:url> and <c:redirect>. This action, if needed, will encode the name and value of this parameter.

Syntax#1: <c:param name=”name” value=”value”/>

Syntax#2:<c:param name=”name”>

parameter value</c:param>

Attributes of action <c:url>Name Request Time

ExpressionType Description

name True String Name of the query string parameter.

value True String Value of the parameter.

Body of <c:param> action can contain any JSP content

<c:redirect url="http://google.com"><c:param name="q">

<c:out value="SimpleSearch"/></c:param>

</c:redirect>

SCWCD Material©2007 IBM Corporation

Page 193: SCWCD 1.4 Material

SCWCD Material 193

Security

In web applications since the clients can access from anywhere security becomes very important issue to be considered. There are both good and bad guys who can access web-applications and these bad guys can be grouped into following categories:

1. Evil Impersonator: Bad guys who imitates (impersonates) like authenticated people. Thus this group of people tries to access the application without authentication.

2. Naughty Upgrader: Bad guys who tries to access parts of application to which they are not authorized.

3. Evil Eavesdropper: Bad guys who hack other people (authorized) information (passwords, credit card #, etc).

Security Mechanisms

In order to secure web-applications following security mechanisms can be used:1. Authentication: Authentication is a process in which user proves to the server to

be the one whom he claims to be. The standard way is username and password, but can include other advanced mechanisms like retina-scan, smart card, etc.

In Web Applications, this is taken care by the logging mechanisms. And this mechanism is against treats given by “Evil Impersonators”.

2. Authorization: Authorization means checking whether a particular identified user is allowed to access a resource. Generally this will be based on the user security clearance, in other words depends on his roles.

In Web Applications, this is taken care by the defining roles for secured resources.

3. Data Integrity: Data Integrity means that the data sent by the source is sent to destination without any alterations/modifications by third-person.

In Web Applications, this is taken care by the restricting the communication mechanisms to be used to access secured resource.

4. Confidentiality: Confidentiality means to ensure that data sent by first person to second person is not accessible to any other third-person.

SCWCD Material©2007 IBM Corporation

Page 194: SCWCD 1.4 Material

SCWCD Material 194

In Web Applications, this is taken care by the restricting the communication mechanisms to be used to access secured resource.

Realm

Before getting into authentication process it is important to understand what “realm” is. Realm is database/mechanism maintained by the containers about the users, their passwords and their role names. Tomcat for example by default maintains this information in “<tomcat dir>/conf/tomcat-users.xml” file.

tomcat-users.xml

<tomcat-users> <role rolename="other"/> <role rolename="tomcat"/> <role rolename="role1"/> <role rolename="manager"/>

<user username="tomcat" password="tomcat" roles="tomcat"/> <user username="role1" password="tomcat" roles="role1"/> <user username="both" password="tomcat" roles="tomcat,role1"/> <user username="kiran" password="kiran" roles="other"/> <user username="kranthi" password="kranthi" roles="manager"/>

</tomcat-users>

But most of the containers provide realm-mechanisms that can be customized and hook/query client database for authentication details.

A container can specify what default realm to be used.

SCWCD Material©2007 IBM Corporation

Page 195: SCWCD 1.4 Material

SCWCD Material 195

Security related part diagram of web.xml

Authentication

Before checking for authorization of user container needs to know who the user it is dealing with. So authentication is the first step container performs when it encounters request for constrained resource.

Authentication is nothing but specifying what log-in process should be used to authenticate user. Following are the 4 types of authentication mechanisms used by J2EE containers.

1. BASIC: Not secured. Uses Base-64 encryption (no encoding is used). In this target server is not authenticated.

SCWCD Material©2007 IBM Corporation

Page 196: SCWCD 1.4 Material

SCWCD Material 196

2. DIGEST: Not secured. Similar to BASIC but the information is encoded and sent to server. Since this mechanism is rarely used, this is not mandated by J2EE specification. So most of the containers may not support this mechanism.

3. CLIENT_CERT: Highly secured mechanism and this requires user to possess “Public Key Certificate” (PKC). Uses HTTP over SSL and SSL take care of encryption. Both server and client (optional) can authenticate each other using PKC. Since PKC is mandatory this mechanism is rarely used.

4. FORM: Lease secure in the available mechanism. But in this mechanism instead of using browser provided dialog box developer can provide customized login and error pages.

First 3 methods differ from each in terms security level provided by these mechanisms in transferring user-name/password information to the server. Whereas the last method is meant for customization.

Configuring Authentication Mechanism

Following example shows how to configure first 3 mechanisms (BASIC, DIGEST & CLIENT_CERT) in web.xml

<web-app version="2.4">.........

<login-config><!—The method can be BASIC, DIGEST or CLIENT_CERT or FORM --><auth-method>DIGEST</auth-method>

</login-config> </web-app>

In these mechanisms whenever client tries to access secured resource following dialog (browser-specific) will get displayed.

SCWCD Material©2007 IBM Corporation

Page 197: SCWCD 1.4 Material

SCWCD Material 197

Configuring FORM Authentication Mechanism

For FORM method developer needs to specify the login and error pages as shown in below example.

<web-app version="2.4">.........

<login-config><auth-method>FORM</auth-method><form-login-config>

<form-login-page>/login/login.html</form-login-page><form-error-page>/login/error.html</form-error-page>

</form-login-config></login-config>

</web-app>

The login page being configured in FORM method authentication should follow following rules:

The user name field should be named as “j_username”. The password field should be name as “j_password”. And the form action should be “j_security_check”. This is needed so that

authentication process can work for all secured resources irrespective of their URL patterns.

<html>

SCWCD Material©2007 IBM Corporation

Page 198: SCWCD 1.4 Material

SCWCD Material 198

<head><title>Simple Test Login page</title>

</head>

<body>Please enter following details:<BR><BR><form action="j_security_check" method="post">

User Name: <input type="text" name="j_username"/><BR>Password: <input type="password" name="j_password"/><BR><input type="submit" value="Submit"/>

</form></body>

</html>

Important Points If no authentication information is specified then no user is allowed to access

any of the secured resources. A container can have multiple realms. We can specify which realm to be used

as shown below.

<login-config><auth-method>DIGEST</auth-method>

<realm-name>otherRealm</realm-name><form-login-config>

<form-login-page>/login/login.html</form-login-page><form-error-page>/login/error.html</form-error-page>

</form-login-config></login-config>

Authorization

Authentication process is triggered when the user tries to access constrained resource. Constraining/restricting a set of resources to a set of user-roles is the way in which authorization is defined.

Configuring secured resource in web application (in web.xml) consists of two steps:

SCWCD Material©2007 IBM Corporation

Page 199: SCWCD 1.4 Material

SCWCD Material 199

1. Defining the roles: This step constitutes of configuring list of roles used by this application using <security-role> element. These roles are mapped by container to the roles in the realm in use.

2. Defining constraints: This step defines the security constraints on set of resources using <security-constraint> element. This step in turn can be divided into following two steps:

a. Defining Resources: This step configures the resources that need to be constrained when specified HTTP methods are used to access them. This is done by using <web-resource-collection> element.

b. Defining Authorized Roles: Configuring roles of users who can access these resources using specified methods. This is done using <auth-constraint> element.

<!-- This constraint says that /test1 & /test3 resources when accessedby GET or POST, users should posses "manager" role.

--><security-constraint> <web-resource-collection> <web-resource-name>test_1_3</web-resource-name> <url-pattern>/test1/*</url-pattern> <url-pattern>/test3/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>manager</role-name> </auth-constraint></security-constraint>

<!-- This constraint says that /test2 resources when accessedby GET or POST, users should posses wither "manager" or "other" role.

--><security-constraint> <web-resource-collection> <web-resource-name>test_2</web-resource-name>

SCWCD Material©2007 IBM Corporation

Page 200: SCWCD 1.4 Material

SCWCD Material 200

<url-pattern>/test2/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>other</role-name> <role-name>manager</role-name> </auth-constraint></security-constraint>

<!-- Defining roles used by this application. This will be usedby container to map this roles to roles in the realm being used.

--><security-role>

<role-name>manager</role-name><role-name>other</role-name>

</security-role>

Following are the important points regarding HTTP methods configuration: If no HTTP methods are specified (using <http-method> in <web-resource-

collection>) that means NO HTTP method is allowed for any one in any role. If at least one HTTP method is specified that means only that method is

constrained. Other HTTP methods can access this resource by any one in any role.

Note we can have more than one <web-resource-collection> element in a single <security-constraint> element.

Following are the important points regarding <auth-constraint> If there is no <auth-constraint> element that means everybody (all roles) can

access these resources. If an empty <auth-constraint> is defined with out any role then that means no

one (no role) can access these resources. These resources are meant for internal usage of application.

Example, <auth-constraint/>

If there is an <auth-constraint> element with role “*” it is equivalent to having no <auth-constraint>. And everybody (all roles) can access these resources.

Example,<auth-constraint>

SCWCD Material©2007 IBM Corporation

Page 201: SCWCD 1.4 Material

SCWCD Material 201

<role-name>*</role-name></auth-constraint>

If multiple <security-constraint> elements are defined for same resource with same methods but with different roles (different <role-name> under <auth-constraint>) then following rules apply:

If one of the <security-constraint> is having no <auth-constraint> or <auth-constraint> with “*” role then any one (any role) can access the resource.

If one of the <security-constraint> is having empty <auth-constraint> then no one (with any role) can access this resource.

Otherwise the union of the roles (all roles defined in all <security-constraint>/<auth-constraint>) can access the resource.

If both empty constraint and constraint with “*” role is encountere then no one (with any role) will not be allowed to access these resources.

Data Integrity & Confidentiality

Both data integrity and confidentiality can be achieved by selecting appropriate transport mechanisms. Following are the three mechanisms available:

1. NONE: This is the default one and means no data protection.2. INTEGRAL: Data integrity needs to be maintained.3. CONFIDENTIAL: Data should not be accessible to the third-person.

Both INTEGRAL and CONFIDENTIAL can be achieved using SSL. And almost all the containers use SSL to achieve INTEGRAL and CONFIDENTIAL mechanisms. Thus specifying one of them will achieve both. But as per J2EE specification the mechanisms are different.

Following example shows how to configure these mechanisms

SCWCD Material©2007 IBM Corporation

Page 202: SCWCD 1.4 Material

SCWCD Material 202

<web-app version="2.4">..........

<security-constraint> <web-resource-collection> <web-resource-name>test_2</web-resource-name> <url-pattern>/test2/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth-constraint> <role-name>other</role-name> <role-name>manager</role-name> </auth-constraint> <user-data-constraint> <!-- This value can be NONE or INTEGRAL or CONFIDENTIAL --> <transport-guarantee>INTEGRAL</transport-guarantee> </user-data-constraint></security-constraint>

..........</web-app>

How it worksWhen a user requests for a secured resource whose transport mechanism is configured to be INTEGRAL/CONFIDENTIAL following steps take place:

Container checks whether the request came from secure communication (HTTPS). If not, container sends error 301 (requesting client (browser) to user secure protocol for communication).

When user request for this resource using secure protocol (HTTPS) then user checks for authentication using configured mechanism. This authentication process also gets performed using secured protocol.

Once authenticated then user is cross checked for authorization.

Thus when FORM authentication mechanism is used (which is not secured at all but provides customization) developer can specify INTEGRAL/CONFIDENTIAL transport mechanism so that customized login mechanism can be obtained in secured way.

SCWCD Material©2007 IBM Corporation

Page 203: SCWCD 1.4 Material

SCWCD Material 203

Programmatic Security

J2EE allows programmatic control on Authentication and Authorization security mechanisms. Following is the list of method in HttpServletRequest which can be used for this purpose:

1. String getUserPrincipal(): This method is used with EJBs.

2. String getRemoteUser(): This will return the logged user name and which in turn can be used for authentication purposes.

3. boolean isUserInRole(String roleName): This will return true if the logged user belongs to specified role. Before this method call, authentication mechanism should have been performed. Otherwise this will return false. This method can be to programmatic authentication on only certain program blocks.

In web.xml we can specify alias name for role names. For example consider following

<web-app version="2.4"><servlet>

<security-role-ref><role-name>manager</role-name><role-link>admin</role-link>

</security-role-ref>..........

</servlet></web-app>

In the above web.xml we defined a new name “manager” for role “admin”. When isUserInRole() method is called with a specific role name

Container will search for the specified name (say for example “manager”) in <security-role-ref>

If a mapping is found then the mapped role name will be used for checking (that is in above example a check will be performed with the mapped role “admin” and isUserInRole() will return true only if logged user belong to “admin” role). This also means that even if a real role exists with specified name (“manager”) that will not be used instead the mapped role (“admin”) will be used.

If no mapping found then the actual role (“manager”) will be used for check (that is isUserInRole() will return true only if logged user belong to “manager” role).

SCWCD Material©2007 IBM Corporation

Page 204: SCWCD 1.4 Material

SCWCD Material 204

J2EE Patterns

Model-View-Controller

Problem

SCWCD Material©2007 IBM Corporation

Page 205: SCWCD 1.4 Material

SCWCD Material 205

Generally enterprise applications need to multiple types of clients/interfaces – HTML interface for web customers, WML front-end for wireless customers and Java Swing interface for administrators and web-services for suppliers.

For single type of client, it may be beneficial to interweave data access and business rules logic with interface-specific logic for presentation and control.

For multiple types of clients, different applications need to be developed, one to support each type of client interface. Non-interface-specific code is duplicated in each application, resulting in duplicate efforts in implementation (often of the copy-and-paste variety), as well as testing and maintenance. The duplication efforts are inevitably imperfect.

SolutionBy applying MVC architecture to J2EE applications we can separate the core business logic, presentation and control logics. Such implementation allows the application to have multiple views (multiple client types) to share same enterprise data model and even control logic if appropriate.

SCWCD Material©2007 IBM Corporation

Page 206: SCWCD 1.4 Material

SCWCD Material 206

Model: Represents the core business logic and holds the code to access the actual business data. EJB falls into this tier.

View: This is the tier with which user interacts. This takes the responsibility of presenting data and maintains consistency irrespective of changes in control or business logic.

Control: Controller translates the interactions with the view into actions to be performed on the model part. Again depending on the user interaction and outcome of model action appropriate view will be presented to the user.

Instead of having multiple servlets, a single servlet (controller) can be used to make control more manageable. This strategy is called “Centralized Controller”.

Advantages By separating view and model components, multiple views can reuse the same

model components. Which in turn makes the model components easier to implement, test and maintain.

Since the control logic is separated, supporting different types of clients (with different types of UI) can be supported with the same controller logic.

SCWCD Material©2007 IBM Corporation

Page 207: SCWCD 1.4 Material

SCWCD Material 207

J2EE Core Patterns

SCWCD Material©2007 IBM Corporation

Page 208: SCWCD 1.4 Material

SCWCD Material 208

Above figure shows how core J2EE patterns interact with each other. Patterns are nothing but the repeated approaches followed in most successful projects to solve certain issues and achieve certain benefits.

Intercepting Filter

ProblemIn web application it is a common requirement to have pre and post processing of the request.

Following is the list of common requirements related to pre processing:1. Check whether the user making the request is authenticated.2. Check whether the user session is valid.3. Check whether the user is accessing from secured network.4. Check whether user is authorized for particular resource5. Decode/uncompress the request data.6. Log the time, requested resource and the user details.7. Does the application supports client tool (browser) used by user

And following is the list of common requirements of post-processing:1. Encode/compress the response2. Log the time, resource and user details.

SolutionUse filters, which can offer pre and post processing. As shown in the “Core Patterns Diagram” all the client requests should go through “Interception Filter” and in the reverse way all the responses going to the client also should go through the “Interception Filter”.

“Interception Filter” need not single filter, it can compose multiple filters according to the needs for different resources.

SCWCD Material©2007 IBM Corporation

Page 209: SCWCD 1.4 Material

SCWCD Material 209

Advantages Filters are pluggable. They need simple configuration in “deployment descriptor”. Multiple filters can be employed depending on the needs for different resources

(level of security). Filters are independent of the main business code/logic. Multiple filters can be employed to distribute the functionality.

Example Implementation

public class CustomFilter implements Filter{

..........

..........public void doFilter(ServletRequest req, ServletResponse res,FilterChain chain)

throws IOException,ServletException {

/*Code for pre-processing*/Logger.log(req);//log user, request informationDecodeEncoder.decode(req);//Decode request..........filterChain.doFilter(req,res);/*Code for post-processing*/Logger.log(res);//log response details and timeDecodeEncoder.encode(res);

}}

Front Controller

ProblemIt is very much needed to have centralized control to serve requests and to control the flow to the views. In the absence of this centralized control following problems are very much expected:

1. Each view needs to provide its own system services (like check for user authentication, session validation, logging and others) often resulting in repeated code.

2. The code needed for view navigation is left to views. Due to this views get tightly coupled with other view components.

3. Distribution control is often hard to maintain, because changes will result in modifications at multiple places.

SCWCD Material©2007 IBM Corporation

Page 210: SCWCD 1.4 Material

SCWCD Material 210

SolutionUse a centralized controller (Servlet) as an initial point of contact for the request. And this controller should be responsible for system services (related to security), delegating business processing, managing choice of appropriate view, handling errors and managing the selection of content creation strategies.

An application can have multiple controllers to serve distinct services.

Advantages

By centralizing decision points, business logic (java code) can be eliminated in the view pages (in JSP these are scriptless).

With help of dispatcher, the controller can choose the next view to be presented to the user.

Due centralization of code, reusability is increased and repeated code is eliminated (which is more error prone).

Struts follow this strategy and uses configuration data (XML files) to make decision on the view selection.

Service Locator

ProblemIn J2EE application all the components are provided as services, which can be accessed through JNDI tree. For example

EJB clients uses JNDI to access EJB home EJB access JNDI to access other EJBs and connection pools. JMS uses JNDI to access Queue and Topics.

In order to obtain these services JNDI will be accessed from multiple places. Due to which following problems are faced:

1. Repeated coding to access JNDI.2. Looking up for initial context will involve lot of processing and resource

usage. This is especially true if the services are located in a different tier.3. Looking for “Initial Context” may also involve usage vendor supplied

context-factory. Due to which application becomes vendor-dependent.4. Looking and creation of service components might be complex logic.

Which tend to repeat across the application repeatedly.

SCWCD Material©2007 IBM Corporation

Page 211: SCWCD 1.4 Material

SCWCD Material 211

SolutionUse “Service Locator” instance, which abstracts all JNDI usage and complexities of initial context creation, lookup for EJB Home and EJB Object re-creation.

Advantages Reduces the complexity in client code (in terms of accessing services). Provides a single point of control. Performance can be improved by reusing “Initial Context” object, reusing EJB

Home objects, providing caching facility of service components, etc.

Example Implementation

public class ServiceLocator {

private static ServiceLocator me;InitialContext context = null;Cache cache=new Cache();

private ServiceLocator() throws ServiceLocatorException {

try{

context = new InitialContext();}catch(NamingException ne){

throw new ServiceLocatorException(...);}

}

SCWCD Material©2007 IBM Corporation

Page 212: SCWCD 1.4 Material

SCWCD Material 212

// Returns the instance of ServiceLocator classpublic static ServiceLocator getInstance() throws ServiceLocatorException {

if(me == null) me = new ServiceLocator();

return me;}

// Returns the EJBHome object for requested service // name. Throws ServiceLocatorException If Any Error // occurs in lookuppublic EJBHome getHome(String name, Class clazz) throws

ServiceLocatorException {

if(cache.contains(name))return (EJBHome)cache.get(name);

try{

Object objref = context.lookup(name);EJBHome home = (EJBHome)

PortableRemoteObject.narrow(objref, clazz);cache.add(name,home);return home;

}catch(NamingException ex) {

throw new ServiceLocatorException(...);}

}}

Business Delegate

ProblemPresentation tier components directly interact with “business services”. Due to which, the business services are exposed across the business tier resulting in “tight coupling” between the business tier and presentation tier. And since the business tier tends to change frequently (due to business logic evolution), presentation components are also vulnerable for changes.

SCWCD Material©2007 IBM Corporation

Page 213: SCWCD 1.4 Material

SCWCD Material 213

SolutionUse a business delegate to reduce coupling between the presentation tier and the business services.

Advantages Hides the complexity of lookup details of business services. Due to removal of tight-coupling between the presentation and business layers,

the changes needed to presentation components due to service changes reduces a lot.

Delegate may cache the service exceptions (remote exceptions) and convert them into application-level exceptions, which are user-friendlier for applications.

Delegate may also transparently perform any retry or recovery operations necessary in the even of the service failure without exposing the client about the problem until it is determined that problem is not resolvable.

Delegate can cache the results and references to business services. Which in turn reduces network traffic to a great extent.

Delegate can also hide complex relationships like lookup actions (but preferably this coding should be performed in “Service Locator”).

When used in combination with “Session Façade”, there will be one-to-one relation between the delegate and “Session Façade”.

Delegate pattern can be used to reduce coupling between any two tiers. It need not be business and presentation tiers.

Example Implementation

public class ResourceDelegate {

private static final Class homeClazz=ResourceSessionHome.class;private ResourceSession session;private Cache cache=new Cache();

// Default Constructor. Looks up home and connects// to session by creating a new onepublic ResourceDelegate() throws ResourceException

SCWCD Material©2007 IBM Corporation

Page 214: SCWCD 1.4 Material

SCWCD Material 214

{try{

ResourceSessionHome home=(ResourceSessionHome)ServiceLocator.getInstance().getHome("Resource",

homeClazz);session = home.create();

}catch(ServiceLocatorException ex) {

throw new ResourceException(...);}catch(CreateException ex) {

throw new ResourceException(...);}catch(RemoteException ex){

throw new ResourceException(...);}

}

public Resource getResource(String name){

if(cache.contains(name))return (Resource)cache.get(name);

Resource res=session.getResource();cache.add(name,res);return res;

}}

Transfer Object

ProblemGenerally client invokes business component’s (Session & Entity beans) methods multiple times to get different attributes. Every method call involves communication across the network, which in turn results in network traffic and hence degrades performance.

For instance, in the example below in order to get complete employee information client has to make three method calls on EmployeeBean (a business component).

SCWCD Material©2007 IBM Corporation

Page 215: SCWCD 1.4 Material

SCWCD Material 215

public class EmployeeBean implements EjbObject{

private String name;private String age;private double pay;

.....

.....public void getName(){

return name;}public void getAge(){

return age;}public double getPay(){

return pay;}

}

Solution

Use “Transfer Object” to encapsulate the business data so that the clients can receive or send the business data in one method call.

Business components are responsible for construction of this transfer objects and populate them with appropriate data and send them back.

SCWCD Material©2007 IBM Corporation

Page 216: SCWCD 1.4 Material

SCWCD Material 216

Advantages

1. Reduces number of method calls on business components. Hence reduction of network traffic.

2. Since transfer object are sent to/from client by value, the method invocations on these objects are local calls not remote.

Example Implementation

public class EmployeeTransferObject{

private String name;private String age;private double pay;

.....public void getName(){

return name;}public void getAge(){

return age;}public double getPay(){

return pay;

SCWCD Material©2007 IBM Corporation

Page 217: SCWCD 1.4 Material

SCWCD Material 217

}}

public class EmployeeBean implements EjbObject{

private String name;private String age;private double pay;

.....public void getEmployee(){

EmployeeTransferObject emp=new EmployeeTransferObject();.... //populate empreturn emp;

}}

In this example, client needs to make only single method call on business component (EmployeeBean) to get complete employee information (getEmploye()).

Deployment Descriptor

The root of the web application descriptor file is <web-app>. Its important to note that other than the root element (<web-app>) none of the other elements will contain attributes. Even the simple properties are specified as sub-elements.

Root element

The root of the deployment descriptor is <web-app>. This element has a mandatory attribute “version” to define which schema version this deployment descriptor conforms to.

Note: All the elements which come directly under <web-app> can occur or multiple times.

The sub-elements of the <web-app> can be grouped and described as follows:

Following is the list of symbols used and their descriptions:

Zero or one occurrences.Zero or multiple occurrences.

Have an optional attribute “xml:lang” which defines the language. Default value is “en” (English).

SCWCD Material©2007 IBM Corporation

Page 218: SCWCD 1.4 Material

SCWCD Material 218

Contains attributes other than “xml.lang”.

One or more times.

SCWCD Material©2007 IBM Corporation

Page 219: SCWCD 1.4 Material

SCWCD Material 219

Application level Properties

Property (multi-

occurrence)

Sub-properties Description

<icon> (*) <small-icon> (?)(16 X 16)

SCWCD Material©2007 IBM Corporation

Page 220: SCWCD 1.4 Material

SCWCD Material 220

Images that can be used by containers UI to represent applications. The paths mentioned (from web application root) should indicate GIF/JPEG images.

<large-icon> (?)(32 X 32)

<display-name> (*)

None Short name for the application that can be used by container UI to represent application.

This has optional attribute “xml:lang” which defines the language. Default value is “en” (English).

<description> (*) None Description about the application.

This has optional attribute “xml:lang” which defines the language. Default value is “en” (English).

<distributable> (*)(true or false)

None Indicates that the web-application is programmed to work in distributed container environment.

<context-param> (*).

<param-name> Defines the initialization parameters that can be accessed from servlet context. <param-value>

<description> (?)<listener> (*) <description> Should be the class name implementing one of the

following listeners in order to get appropriate notifications:

javax.servlet.ServletContextListener javax.servlet.ServletContextAttributeListener javax.servlet.ServletRequestListener javax.servlet.ServletRequestAttributeListener javax.servlet.http.HttpSessionAttributeListene

r javax.servlet.http.HttpSessionListener

<display-name>

<icon>

<listener-class>

<session-config> (*)

<session-timeout> (?)

If not specified or <= 0, then session will never get timed out.

This value specifies the time-out for sessions in this application in minutes.

<mime-mapping> (*)

<extension> A string describing extension like “txt”, “pdf”<mime-type> String representing mime type like “text/html”,

“image/gif”<welcome-file-list> (*)

<welcome-file> (+) Order list of welcome files.

<error-page> (*) <error-code> Defines the HTTP error-code. This is mandatory if <exception-type> is not specified.

<exception-type> Defines fully specified exception type. It is mandatory if <error-code> is not defined.

<location> Resource location of the web-application. This value should start with “/”

SCWCD Material©2007 IBM Corporation

Page 221: SCWCD 1.4 Material

SCWCD Material 221

<locale-encoding-mapping-list> (*) / <locale-encoding-mapping> (+)

<locale> Locale to be mapped.

<encoding> Character-encoding for specified locale.

Welcome File(s): List of welcome files defined by <welcome-file-list> is the list of partial URLs. When a request is made by the client with a directory entry in web-application not mapped to any resource, then each entry in the welcome-file partial URL list is appended to the request-folder-uri and checked for static/dynamic resource. If found request will be forwarded to that resource (which matched first in the list).

Filter related properties

SCWCD Material©2007 IBM Corporation

Page 222: SCWCD 1.4 Material

SCWCD Material 222

Property (multi-occurrence)

Sub-properties Description

<filter> element<icon> (?) Icon to represent this filter.<filter-name> None Name of the filter.<display-name> (?) None Short name for the filter used by container UI.<description> (?) None Description for the filter.<filter-class> None Name of the filter class.<init-param> (*) <name> Init parameters for the filter, which can be

accessed from FilterConfig.<value>

<filter-mapping> element<filter-name>

NoneName of the filter for which mapping needs to be defined.

<url-pattern>

None

Required if <servlet> is not used.

Specifies URL patterns for which this filter needs to be used.

<servlet>

None

Required if <url-pattern> is not used.

The name of the servlet which, if called, this filter should be invoked.

<dispatcher> (*)

None

Can hold one of the following values:

1. FORWARD : Filter will be used when RequestDispatcher.forward() is used with matching URL-pattern or servlet.

2. REQUEST : Filter will be applied under ordinary client calls to the matching URL or servlet.

3. INCLUDE: Filter will be used when RequestDispatcher.include() is used with matching URL-pattern or servlet.

4. ERROR: Filter will be applied under error page mechanism.

REQUEST is the default functionality.

SCWCD Material©2007 IBM Corporation

Page 223: SCWCD 1.4 Material

SCWCD Material 223

Servlet related properties

Property (multi-occurrence)

Sub-properties Description

<servlet> (*)<icon> (?) Icon to represent this servlet.<servlet-name> None Name of the servlet.

SCWCD Material©2007 IBM Corporation

Page 224: SCWCD 1.4 Material

SCWCD Material 224

<display-name> (?) None Short name for the servlet used by container UI.<description> (?) None Description for the servlet.<servlet-class>

NoneRequired if <jsp-file> is not used.

Name of the servlet class.<jsp-file>

None

Required if <servlet-class> is not used.

The JSP file path from the application root. The path should start with “/”.

<load-on-startup> (?)

None

Should be an integer. Servlets with negative numbers will be loaded whenever needed.

If zero or positive value is specified then this servlet will be initialized (init() will get called) when web-application gets started.

Servlets with lower values will be loaded first. If this servlet represents JSP and this value is >=0 then JSP gets pre-compiled and get initialized.

<run-as> (?)None

Identity to be used for the execution of this component.

<security-role-ref> (*) <description> (?) Description of the role.

<role-name>Defines the name of the security role that is used in servlet code.

<role-link> (?)Defines the name of the security role that is defined in <security-role>

<servlet-mapping> (*)<servlet-name>

None

The name of the servlet for which mapping needs to be defined.

For multiple mappings per servlet, multiple <servlet-mapping> should be specified.

<url-pattern>None

URL mappings for which servlets needs to be invoked.

SCWCD Material©2007 IBM Corporation

Page 225: SCWCD 1.4 Material

SCWCD Material 225

JSP Related Properties

Property (multi-occurrence)

Sub-properties Description

<jsp-config> (*)<taglib> (*)

Defines the custom tag library. <tablib-url>

URL for representing this tag library. The URL can be simple context-type URL (starting with “/”) or it can be absolute URL (www.kranthi.com)

This URL will be used in JSP or TAG files to refer to this custom tag library.

<taglib-location>Location of TLD file in the application. This value should start with “/”.

<jsp-property-group> (*)

<description> (*)<display-name> (*)

SCWCD Material©2007 IBM Corporation

Page 226: SCWCD 1.4 Material

SCWCD Material 226

Defines properties for the group of JSP files marching specified URL.

<url-pattern>

URL pattern for this JSP group.

If this patter is not ending with jsp (eg *.svg) then all the resources matching this pattern are trated as JSP files.

<is-xml> (?)

(true/false)

Specifies whether this group of JSP files are standard JSP files or JSP documents (in XML format).

<el-ignored> (?)

(true/false)

Specifies whether EL expressions should be ignored in these JSP files.

<scripting-invalid> (?)

(true/false)

Specifies whether scripting elements in these JSP files are invalid.

<page-encoding> (?)

Default page encoding for these JSP files.

<include-preclude> (?)

Default header file for these JSP files.

This should be a resource path starting with “/”

<include-coda> (?)Default footer file for these JSP files.

This should be a resource path starting with “/”

Security Related Properties

SCWCD Material©2007 IBM Corporation

Page 227: SCWCD 1.4 Material

SCWCD Material 227

Property (multi-occurrence)

Sub-properties Description

<security-constraint> (*)<display-name> (*)<web-resource-collection> (*)

<web-resource-name>

Name for the resource collection.

<description> (*)

<url-pattern> (+)Defines set of resources (resources matching specified URL pattern) to which this constraint should be applied.

<http-method> (*)HTTP methods on specified resources to which this constraint should be applied.

<auth-constraint> (?) <description> (*)

SCWCD Material©2007 IBM Corporation

Page 228: SCWCD 1.4 Material

SCWCD Material 228

<role-name> (*)

Roles that are authorized to access specified resources with specified HTTP methods.

This name should match with one of the roles defined by <security-role> or it should be “*” (indicating all roles defined in this application).

If no roles are defined, then set of resources with specified HTTP methods are not accessible to ant one.

Role names are case sensitive.<user-data-constraint> (?)

<description> (*)

<transport-guarantee>

Defines how data communicated between client and application should be protected. The legal values for these are:

NONEINTEGRALCONFIDENTIAL

<login-config> (*)<auth-method> (?) Defines authentication method for the web-

application. Valid values are BASICDIGESTFORMCLIENT-CERT

<realm-name> (?) The realm name to be used in HTTP BASIC authentication.

<form-login-config> (?) <form-login-page>

Login page for FORM based authentication.

<form-error-page>

Error page for FORM based authentication.

<security-role> (*)<description> (*)<role-name> The name must conform with lexical rules of

NMTOKEN.

Environment Related Property

SCWCD Material©2007 IBM Corporation

Page 229: SCWCD 1.4 Material

SCWCD Material 229

Property (multi-occurrence)

Sub-properties Description

<env-entry> (*)

Using this property we can bind an object to JNDI tree.

<description> (*)

<env-entry_name>

JNDI name relative to java:comp/env.

<env-entry-type> Fully specified java class name.

<env-entry-value> (?)

The value for this environment entry. This value must be a String that is valid for the constructor of the specified type that takes String as a parameter or a single character for java.lang.Character

EJB related Properties

SCWCD Material©2007 IBM Corporation

Page 230: SCWCD 1.4 Material

SCWCD Material 230

Property (multi-occurrence)

Sub-properties Description

<ejb-ref> (*)

Defines the reference to an EJB component.

<description> (*)

<ejb-ref-name>

JNDI name that the servlet code uses to get the reference to this EJB.

This is relative to java:comp/env context. It is recommended to have this value prefixed by “ejb/”

<ejb-ref-type>Expected type of the referenced EJB. This should be either Entity or Session.

<home> Fully qualified name of the EJB home interface.<remote> Fully qualified name of the EJB remote interface.

SCWCD Material©2007 IBM Corporation

Page 231: SCWCD 1.4 Material

SCWCD Material 231

<ejb-link> (?)

Specifies the name of EJB this reference should refer to.

This value should be the name of the EJB (ejb-name) as defined in ejb-jar.xml of the EJB jar file.

<ejb-local-ref> (*)

Defines the reference to a local EJB component.

<description> (*)

<ejb-ref-name>

JNDI name that the servlet code uses to get the reference to this EJB.

This is relative to java:comp/env context. It is recommended to have this value prefixed by “ejb/”

<ejb-ref-type>Expected type of the referenced EJB. This should be either Entity or Session.

<home> Fully qualified name of the EJB home interface.<remote> Fully qualified name of the EJB remote interface.

<ejb-link> (?)

Specifies the name of EJB this reference should refer to.

This value should be the name of the EJB (ejb-name) as defined in ejb-jar.xml of the EJB jar file.

Example:

Web.xml

<ejb-local-ref><ejb-ref-name>ejb/ImportExportSSB</ejb-ref-name><ejb-ref-type>Session</ejb-ref-type><local-home>com.sprint.asdc.ejbs.ImportExportSSBLocalHome</local-home><local>com.sprint.asdc.ejbs.ImportExportSSBLocal</local><ejb-link>ASDCEarEJB.jar#ImportExportSSB</ejb-link>

</ejb-local-ref>

Java Code for getting EJB home:

InitialContext ic = new InitialContext();EJBLocalHome home= (EJBLocalHome) ic.lookup(“java:comp/env/ejb/ImportExportSSB”);

SCWCD Material©2007 IBM Corporation

Page 232: SCWCD 1.4 Material

SCWCD Material 232

JMS related properties

SCWCD Material©2007 IBM Corporation

Page 233: SCWCD 1.4 Material

SCWCD Material 233

Web Services Related Property

Other Properties

SCWCD Material©2007 IBM Corporation

Page 234: SCWCD 1.4 Material

SCWCD Material 234

Important Points

The only JNDI reference nodes in web applications are defined by <ejb-ref> and <res-ref>.

Web application should not override container implementation classes otherwise results are ambiguous.

SCWCD Material©2007 IBM Corporation

Page 235: SCWCD 1.4 Material

SCWCD Material 235

Last Minute Notes

1. Note the following difference in the methods. In request objectgetParameterValues(String paramName) returns String[]getHeaders(String headerName) retruns Enumeration

Note the diference in method name patterns.“Parameter Names” are case-sensitive.“Header Names” are case-insensitive.

2. In web.xml session time-out is specified in minutes whereas programmatic session time-out (HttpSession.setMaxInterval()) is in seconds.

3. For a given request among matching filters, filters mapped with “url-pattern” are invoked before filters mapped with “servlet-name”. And among the filters mapping groups (servlet-name and url-pattern based) the invoking sequence is according to the sequence in which they are configured in web.xml

4. In Filter unlike other 2 life-cycle methods (call-back methods), doFilter() is both call-back and inline method (because it is called by container and even when doFilter() is called on FilterChain).

5. Generally most containers will return 404-error when requested resource is not found but its not mandatory as per J2EE specification.

6. Remember <jsp:include> can be used both for static and dynamic resources.

SCWCD Material©2007 IBM Corporation

Page 236: SCWCD 1.4 Material

SCWCD Material 236

7. JspContext containsMethods related to attributes (find, get, set, remove)getOut()

PageContext (which extend JspContext) containsGetters for implicit objects (request, response, session, page etc)Include/forward functionsMethods for handling functions

8. In WAR file, META-INF directory is not optional (note if not included this directory will be created automatically).

9. When a session attribute is replaced and replaced/replacing attributes both are implementiong HttpSessionAttributeBindingListener, then valueBound() will be called on new session attribute first then valueUnbound() will be called on old session attribute later.

10. EL expressions will never throw arithmetic exceptions (like division by zero, etc) or NullPointerException. The only exceptions thrown by EL expression is due to improper syntax and missing properties.

11. Following methods will throw exception when invoked on invalidated sessionAttribute related methods (set, get, remove)isNew()getID()getCreationTime()invalidate()

Whereas following method will not throw any invocation on invalidated sessiongetServletContext()set and get MaxInactiveInterval

12. Following methods will throw exception when invoked on commited response object

sendError()sendRedirect()setBufferSize()reset()

Note flush() on response writer/OutputStream will commit the response.

13. On response object either of getWriter() or getOutputStream() should be called. If both are invoked second one will throw exception.

14. Response object mainly consists of adders/setters (for header, attributes, status code etc). The only getters available in response object are

Buffer Size

SCWCD Material©2007 IBM Corporation

Page 237: SCWCD 1.4 Material

SCWCD Material 237

Content Type, Char Encoding, localeisCommited()getOutputStream()/getWriter()

15. In EL expressions all the tokens should be java-literals or else should be enclosed in quotes (even for [] operator).

For example,In ${map[map-index]}

“map-index” is no treated as a single token, instead it will be treated as “map minus(-) index”.

16.

Tag Simple Tagint doEndTag()int doStartTag()

Tag getParent()void setParent(Tag)

void release()

void setPageContext(PageContext)

Iteration Tag

int doAfterBody()

Body Tag

void setBodyContent(BodyContent)void doInitBody()

void doTag()

JapTag getParent()void setParent(JspTag)

void setJspContext(JspContext)

void setJspBody(JspFragment)

SCWCD Material©2007 IBM Corporation

Page 238: SCWCD 1.4 Material

SCWCD Material 238

SCWCD Material©2007 IBM Corporation