Search This Blog

Wednesday, January 20, 2010

Servlet & JSP

Life cycle of Servlet

The life cycle of a servlet can be categorized into four parts:
1. Loading and Inatantiation: The servlet container loads the servlet during startup or when the first request is made. The loading of the servlet depends on the attribute of web.xml file. If the attribute has a positive value then the servlet is load with loading of the container otherwise it load when the first request comes for service. After loading of the servlet, the container creates the instances of the servlet.
2. Initialization: After creating the instances, the servlet container calls the init() method and passes the servlet initialization parameters to the init() method. The init() must be called by the servlet container before the servlet can service any request. The initialization parameters persist untill the servlet is destroyed. The init() method is called only once throughout the life cycle of the servlet.

The servlet will be available for service if it is loaded successfully otherwise the servlet container unloads the servlet.
3. Servicing the Request: After successfully completing the initialization process, the servlet will be available for service. Servlet creates seperate threads for each request. The sevlet container calls the service() method for servicing any request. The service() method determines the kind of request and calls the appropriate method (doGet() or doPost()) for handling the request and sends response to the client using the methods of the response object.
4. Destroying the Servlet: If the servlet is no longer needed for servicing any request, the servlet container calls the destroy() method . Like the init() method this method is also called only once throughout the life cycle of the servlet. Calling the destroy() method indicates to the servlet container not to sent the any request for service and the servlet releases all the resources associated with it. Java Virtual Machine claims for the memory associated with the resources for garbage collection.


Servlet Context

ServletContext is a interface which helps us to communicate with the servlet container. There is only one ServletContext for the entire web application and the components of the web application can share it. The information in the ServletContext will be common to all the components. Remember that each servlet will have its own ServletConfig. The ServetContext is created by the container when the web application is deployed and after that only the context is available to each servlet in the web application.
Web application initialization:
1. First of all the web container reads the deployment descriptor file and then creates a name/value pair for each tag.
2. After creating the name/value pair it creates a new instance of ServletContext.
3. Its the responsibility of the Container to give the reference of the ServletContext to the context init parameters.
4. The servlet and jsp which are part of the same web application can have the access of the ServletContext.
The Context init parameters are available to the entire web application not just to the single servlet like servlet init parameters.
How can we do the mapping of the Context init parameters in web.xml

JSP ARCHITECTURE
JSP pages are high level extension of servlet and it enable the developers to embed java code in html pages. JSP files are finally compiled into a servlet by the JSP engine. Compiled servlet is used by the engine to serve the requests.
javax.servlet.jsp package defines two interfaces:
• JSPPage
• HttpJspPage
These interfaces defines the three methods for the compiled JSP page. These methods are:
• jspInit()
• jspDestroy()
• _jspService(HttpServletRequest request,HttpServletResponse response)

In the compiled JSP file these methods are present. Programmer can define jspInit() and jspDestroy() methods, but the _jspService(HttpServletRequest request,HttpServletResponse response) method is generated by the JSP engine.
Directives :
Listing some of them to start off :
1) Page
Syntax : < %@ page Language=”Java” extends=”” import=” or ” %>
Attributes:
a. Language = “Java”
b. Import = “Class”
c. Buffersize = “”
d. Scope = “REQUEST/PAGE/SESSION/APPLICATION”
e. And etc….
Page directive is aimed to define certain attribute of a JSP page for e.g. Language of the page in which the page content should be written , which class to be imported so that it can be used within the JSP page.
2) Include
Syntax: <%@ include file=”” %>
Attributes:
a. file = “
This directive is to include the a HTML, JSP or Sevlet file into a JSP file. This is a static inclusion of file i.e. it will be included into the JSP file at the time of compilation and once the JSP file is compiled any changes in the included the file will not the reflected.
Declarations:
Syntax: <%! Declare all the variables here %>
Scriplets:
Syntax: <% All your scripts will come here %>
Expressions:
Syntax: <%= expression evaluation and display the variable %>
Standard Action:
Syntax:
Include ” />
This inclusion of file is dynamic and the specified file is included in the JSP file at run-time i.e. out put of the included file is inserted into the JSP file.
Forward ” />
This will redirect to the different page without notifying browser.
And many more.
Custom Tags:
taglib
Syntax: <%@ taglib uri=”” prefix=”” %>
Attributes:
a. uri = “
b. prefix = “
prefix is alias name for the tag library name

Implicit Objects:
Implicit Objects in JSP are objects that are automatically available in JSP. Implicit Objects are Java objects that the JSP Container provides to a developer to access them in their program using JavaBeans and Servlets. These objects are called implicit objects because they are automatically instantiated.

There are many implicit objects available. Some of them are:

request: The class or the interface name of the object request is http.httpservletrequest. The object request is of type Javax.servlet.http.httpservletrequest. This denotes the data included with the HTTP Request. The client first makes a request that is then passed to the server. The requested object is used to take the value from client’s web browser and pass it to the server. This is performed using HTTP request like headers, cookies and arguments.

response: This denotes the HTTP Response data. The result or the information from a request is denoted by this object. This is in contrast to the request object. The class or the interface name of the object response is http.HttpServletResponse. The object response is of type Javax.servlet.http. >httpservletresponse. Generally, the object response is used with cookies. The response object is also used with HTTP Headers.

Session: This denotes the data associated with a specific session of user. The class or the interface name of the object Session is http.HttpSession. The object Session is of type Javax.servlet.http.httpsession. The previous two objects, request and response, are used to pass information from web browser to server and from server to web browser respectively. The Session Object provides the connection or association between the client and the server. The main use of Session Objects is for maintaining states when there are multiple page requests. This will be explained in further detail in following sections.

Out: This denotes the Output stream in the context of page. The class or the interface name of the Out object is jsp.JspWriter. The Out object is written: Javax.servlet.jsp.JspWriter

PageContext: This is used to access page attributes and also to access all the namespaces associated with a JSP page. The class or the interface name of the object PageContext is jsp.pageContext. The object PageContext is written: Javax.servlet.jsp.pagecontext

Application: This is used to share the data with all application pages. The class or the interface name of the Application object is ServletContext. The Application object is written: Javax.servlet.http.ServletContext

Config: This is used to get information regarding the Servlet configuration, stored in the Config object. The class or the interface name of the Config object is ServletConfig. The object Config is written Javax.servlet.http.ServletConfig

Page: The Page object denotes the JSP page, used for calling any instance of a Page's servlet. The class or the interface name of the Page object is jsp.HttpJspPage. The Page object is written: Java.lang.Object



Java Beans
Java Beans are reusable components. They are used to separate Business logic from the Presentation logic. Internally, a bean is just an instance of a class.
JSP’s provide three basic tags for working with Beans.

bean name = the name that refers to the bean.
Bean class = name of the java class that defines the bean.

id = the name of the bean as specified in the useBean tag.
property = name of the property to be passed to the bean.
value = value of that particular property .
An variant for this tag is the property attribute can be replaced by an “ * ”. What this does is that it accepts all the form parameters and thus reduces the need for writing multiple setProperty tags. The only consideration is that the form parameter names should be the same as that of the bean property names.

Here the property is the name of the property whose value is to be obtained from the bean.
BEAN SCOPES :
These defines the range and lifespan of the bean.
The different options are :
o Page scope :
Any object whose scope is the page will disappear as soon as the current page finishes generating. The object with a page scope may be modified as often as desired within the particular page but the changes are lost as soon as the page exists.
By default all beans have page scope.
o Request scope :
Any objects created in the request scope will be available as long as the request object is. For example if the JSP page uses an jsp:forward tag, then the bean should be applicable in the forwarded JSP also, if the scope defined is of Request scope.
o The Session scope :
In JSP terms, the data associated with the user has session scope. A session does not correspond directly to the user; rather, it corresponds with a particular period of time the user spends at a site. Typically, this period is defined as all the visits a user makes to a site between starting and existing his browser.
Objective 5) JSP implicit objects
What are Implicit Objects?
When writing Servlets the available objects are fairly obvious as they are the parameters to methods, thus if you are overriding the doPost method you will have a signature of
public void doPost(HttpServletRequest request,
HttpServletResponse response)
When writing JSP pages the implicit objects are created automatically for you within the service method . You just have to know what the implicit objects are, but as most of them match closely to those available in Servlet methods they are not too difficult to memorise. You will have come across one of the implicit objects already with the out object which allows you to send information to the output stream.
Note that the implicit variables are only available within the jspService method and thus are not available within any declarations. Thus for example the following code will cause a compile time error.
<%! public void amethod(){ out.print("Hello"); } %>
The request and response implicit objects
The request implicit object is an instance of HttpServletRequest, and response is an instance of HttpServletResponse objects. They are available in a similar way to the request and response object passed to the doGet and doPost methods in servlets.
A typical use for the request is to get the details of HTTP query string such as query names and parameters.
<%= request.getQueryString() %>
Will display the query string after the name of the jsp file itself. Thus if this code is within a file called hello.jsp and is called with the url as follows
http://localhost:8080/chap03/hello.jsp?thisisthequerystring
The output will include thisisthequerystring as part of the page.
The response can be used for the same purposes as the HttpServletResponse in a servlet, such as adding cookies or headers.
The request and response objects are the same as the parameters to doPost and represent instances of HttpServletRequest and HttpServletResponse respectively.
The out implicit object
The out implicit object has a type of jsp.JspWriter. The out object can be used in a similar way to System.out is used in plain ordinary Java programs, i.e.
<% out.print("Hello World"); %>
The parameters of out are sent to the output stream, which generally means they end up visible in the browser requesting the JSP page.
session
The session implicit object is an instance of
javax.servlet.http.HttpSession
The session concept is a way of allowing multiple requests from the same client to be group together as part of a single “conversation”. This is a way of getting around the basic architectural limitation within HTTP in that it was designed as a stateless protocol, i.e. web servers “forget” about each client as soon as a request has finished execution. The default way of logically linking multiple requests from the same client is by generating a cookie that stores a value unique to the client. After the first request establishes a session, each subsequent request reads that cookie and can thus identify the unique client.
With the session object you do not need the type of code required in a Servlet whereby you have to call the getSession method to access an existing session or start a new one. Typical uses of the session object are for getting and setting attributes. Thus you can add a new attribute to the session with code like the following.
<% session.setAttribute("username","marcusgreen"); %>
config
The config implicit object is an instance of
javax.servlet.ServletConfig
And represents the parameters set up within the deployment descriptor. To set up the configuration a servlet is configured within web.xml , but instead of creating a element a element is created containing the name of the JSP page. Parameters are then created using the and tags.
The config object can be used to retrieve parameters using its
getInitParameter(String param)
method.
The config object can be used to retrieve the ServletContext object through its getServletContext method. Thus the following code retrieves information about the currently executing server, and in my own setup it generates the output.
Apache Tomcat/5.5.9
<% ServletContext ct = config.getServletContext(); out.print(ct.getServerInfo()); %>
application
The application implicit object is an instance of javax.servlet.ServletContext. It refers to the overall web application environment that the JSP belongs to. According to the API docs
“Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.”
In Apache Tomcat a web application will be contained in an individual directory under the webapps directory. A typical use of the application object is to get access to the application wide initialisation parameters. Because the application and config objects have similar and slightly confusing uses the following code shows how they can be used along with a deployment descriptor (WEB.XML) that sets up the appropriate initialisation parameters for them.
The file index.jsp
<% /*for parameters declared at the application level . *i.e. under the WEB-APP tag of the deployment descriptor */ out.print(application.getInitParameter("myparam")); /*for a specific resource within an application *identified as a servlet in the deployment descriptor */ out.print(config.getInitParameter("myparam2")); %>
The deployment descriptor (WEB.XML)



myparam param1



MyServlet


/index.jsp


myparam2 param2




MyServlet


/index.jsp



The page implicit object
The page implicit object is of type Object and it is assigned a reference to the servlet that executing the _jspService() method. Thus in the Servlet generated by tomcat the page object is created as
Object page = this;
Because page is of type Object it is of less direct use than simply accessing the implicit this object. To access any of the methods of the servlet through page it must be first cast to type Servlet. Thus the two following lines of code are equivalent.
<% this.log("log message"); %>
<% ((HttpServlet)page).log("anothermessage"); %>
As you probably will not be using the page object in your own code the main thing to remember for the exam is that it is not the same as the pageContext object and that it is of type Object.
The pageContext implicit object
The pageContext object has a type of javax.servlet.jsp.PageContext and according to the API documents
“A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically “http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/PageContext.html
So it can be seen as a convenience object for tasks such as transferring requests to other web resources. Much of its functionality appears to be for the convenience of generating the servlet from the JSP, thus the following example of a servlet generated from the Tomcat container shows how PageContext is used to populate other implicit objects.
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
A typical use of the pageContext is to to include another resource or forward to another resource. Thus the following would forward from the current page to menu.jsp
<% pageContext.forward("menu.jsp"); %>
The exception implicit object
The exception implicit object is of type
java.lang.Throwable
This object is only available to pages that have isErrorPage set to true with the directive
<%@ page isErrorPage='true' %>
The exception object refers to the exception triggered by the page that uses this page as an exception handler
The following code demonstrates the use of the exception implicit object. The first page uses the errorPage directive to set up the JSP page to use when an error occurs, and the second page called ErrorPage.jsp uses the isErrorPage directive to set itself up to catch the error.
First page
<%@page errorPage="ErrorPage.jsp" %>
<% int i=10; /*Divide by zero, generates an error */ out.print(i/0); %>
ErrorPage.jsp
<%@ page isErrorPage='true' %>
<% out.print("

Here is the error message

");
out.print(exception.getMessage());
%>
Declarative handling of exceptions
It is also possible to map HTTP error codes and or Java exception types to an error page in the deployment descriptor. This is done at the web application level by using the tag which is a child of the tag. Thus the following tags would re-direct all SQL exception errors to the /errorpage.jsp page.


java.sql.SQLException


/errorpage.jsp


The following tags would re-direct all HTTP 404 errors to the /errorpage.jsp page

404
/errorPage.jsp

Difference between include directive & include action in JSP

include directive - <%@ include file="fileName" %> - as is the case with all other directives in a JSP page, this include directive is also processed at the time when the JSP page is translated into its equivalent servlet. This directive simply causes the contents of the specified file to be pasted into the JSP page at the place where the page contains this directive. Irrespective of whether the included resource is a static resource or a JSP page - only the contents of the file are pasted (and not the processed results). This directive is normally used for including static resources only - like, banner, header, footer, etc. for the obvious reason.

One common issue with include directive (if it's used to include another JSP) is that the main JSP (which calls this directive to include another JSP) doesn't get re-compiled in the case when the included JSP changes but not the main JSP. Reason being, a JSP is re-compiled only if the contents of the JSP changes. Now in this case, the main JSP (after inclusion) remains the same. Once the include directive has been processed during the translation phase, the main JSP is unaware that part of its contents have come from another file. The entire translated file is treated as a single unit. Any changes to the main JSP will initiate the translation phase and then compilation phase again and hence the specified is included again. So, any modification in the included JSP will not get reflected unless the main JSP is also changed.

include action - - this include action is executed at run time and the specified 'page' is first executed and then the result of that 'page' is appended to the response object of the calling JSP at the point where the tag occurs. Obviously if the specified page is a static resource then the contents of it are included as there won't be an executed result in that case. This action allows additional parameters to be passed via child element of this include action element.

Remember that we can specify only a relative URL i.e., a resource which is in the same context as the calling JSP page. Since the resource is called by passing both the request and response objects, hence the called JSP can access any beans defined in the request using the tag. But, this included resource can't set any HTTP headers. This is the reason why an included resource can't set cookies (as they are carried in the HTTP Headers). Such an attempt will throw an exception.

Difference between include directive & include action

• The most evident difference is that include directive is processed at the translation time while the include action is processed at the run time.
• include directive don't require a relative file path (it can be either relative or absolute) whereas the include action requires the page name to be relative to the context of the calling JSP.
• include action always includes the contents of the specified file irrespective of whether the specified file is a static resource or a dynamic resource whereas include action executed a specified dynamic resource and only the result gets included in the response of the calling JSP. In case of static resource even the include action just includes the contents only as in that case the resource can't be executed.
• include directive does not ask for any parameters to be passed, which is quite obvious because include directive doesn't execute the specified resource whereas we may specify additional parameters which may be used while execution of the specified resource in case of include action.
• include directive can't access the objects created in the request scope (in fact, it doesn't need to access any again because it's not going to execute the resource) whereas the include action can access the objects created with the request scope.
JSP’s offer a unique feature of “Tag Libraries”. Simply put, these are custom defined JSP tags. They are basically meant for componentizing presentation level logic. They are very similar to beans except the fact that Beans are used to separate Business logic.
Every tag is mapped to a particular class file which is executed whenever the tag is encountered in an JSP file.
The general syntax :
<%@ taglib uri=“ - - - - - ” prefix = “ - - - ” %>
The parent of the tag is the JSP tag within which it is nested, if there isn’t one, its set to null.
There are two things to remember while using TAGLIB’s :
The Class file should be created and it should be deployed in the Servlet folder of the web server. The class file should implement the Tag and BodyTag interfaces.
The mapping of a particular tag to a particular class file should be done in the taglib.tld file.
The tag is then ready to be used in the JSP file !!
The taglib file forms the central description for the tag library :
This file is an XML document that defines the tag’s operation.
It maps the tag name on the page to the implementing class.
It defines inputs to the class.
It references the helper class that provides details of any output variables set by the tag class.
This Tag and Bodytag have some methods, these all methods are callback methods.
Tag methods: doStartTag()
doEndTag()
Body Tag : doAfterBody()
Let’s have small example to display Hello World :
1. First we write simple jsp file
<% @ taglib uri=”/taglib.tld” prefix=”nt” %>






2. It will look for file specified in uri attribute,that file will be


1.0
1.1
nt

Hello World
mytags.HelloWorld
empty



3. Next this will look for Helloworld .class file will be

Package mytags;
Import javax.servlet.jsp.*;
Import javax.servlet.jsp.tagtext.*;
Public class Helloworld implements Tag {
private PageContext pagecontext;
private Tag parent;
public int doStartTag() throws JSPException {
return SKIP_BODY;
}
public int doEndTag () throws JSPException {
try{
pageContext.getOut().write(“Hello World”);
} catch(java.io.Exception ex) {
throw new JSPException(“IO Exception”);
}
return EVAL_PAGE;
}
public void release (){}
public void setPageContext(pageContext p) {
pageContext=p;
}
public void setParent(Tag t) {
parent = t;
}
public void getParent() {
return parent;
}
}
Flow of programme:
Here in first .jsp file we are writing tag.But name and properties of this tag we are writing in .tld file. And whatever task that tag is going to perform is written in .class file which has been called by .tld file.
So by using taglib we can create our own defined tags.
Writing Servlet Filters
by Kief Morris kief@kief.com
Filters are an under-appreciated feature of the Java servlet platform, ideal for writing components that can be added transparently to any web application. A filter is like a lightweight servlet that doesn't generate its own content, instead it plugs into the request handling process and executes in addition to the normal page processing.
Filters might record information about requests, convert content to a different format, or even redirect access to a different page. Filters can be applied to any resources served by a servlet engine, whether it's flat HTML, graphics, a JSP page, servlet , or whatever. They can be added to an existing web application without either the filter or the application being aware of one another. Filters are essentially a server plug-in that works with any servlet container compliant with version 2.3 or later of the servlet specification.
A filter implements the interface javax.servlet.Filter, and configured in the web application web.xml file, where the URL's it will process are defined. For each request, the servlet container decides which filters to apply, and adds those filters to a chain in the same order they appear in web.xml. Each filter has its Filter.doFilter() method called, and triggers the invocation of the next filter in the chain or the loading of the final resource (HTML page, servlet, or whatever).
Writing a simple filter
To write a filter, we create a class implementing the Filter interface, which requires three methods: init(), doFilter(), and destroy(). init() and destroy() are called when the filter is first initialized and when it is destroyed, respectively, to allow configuration and cleanup. For the moment we'll ignore these and focus on doFilter(), which is the meat of the filter.
Filter.doFilter()
The servlet container calls the filter's doFilter() method and passes request and response objects for the current request. These are the same objects as a servlet gets, but since there is no HttpFilter, the parameters are defined as javax.servlet.ServletRequest and javax.servlet.ServletResponse, rather than the javax.servlet.http subclasses. This means that if you want to access methods available only on the HTTP versions of the request and response classes, you will need to cast the objects. To be a Good Programmer, you should first test that they actually are the HTTP versions, in case future generations want to use your filter in a non-HTTP servlet environment. Some of the code later in this article shows examples of this.
The third parameter to doFilter() is a FilterChain object, which is used to invoke the next filter in the chain. This is done by calling FilterChain.doFilter() and passing it the request and response objects. If the current filter is the last filter in the chain, the destination resource will be accessed, that is, the HTML page or other static file will be read in, or else a servlet or JSP page will be invoked. After FilterChain.doFilter() returns, the filter can do more processing if it chooses; at this point, the response object should have more fields populated, than it did beforehand, such as the content-type header having been set.
TimerFilter is a simple filter which does nothing more than time how long it takes to process the request after the filter, based directly on the Apache Foundation's Tomcat 4.0 server's ExampleFilter. If this filter is placed as the last filter in the chain, it times the servlet execution or page access itself. Here is the doFilter() method:
public final class TimerFilter implements Filter
{

public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException
{

long startTime = System.currentTimeMillis();
chain.doFilter(request, response);
long stopTime = System.currentTimeMillis();
System.out.println("Time to execute request: " + (stopTime - startTime) +
" milliseconds");

}
...
To compile a Filter you will need to link it with the servlet API classes, which include the interface definitions and other classes used by the filter. These classes are almost certainly available with your servlet container; typically named servlet.jar. If you download the sample source code for this article you can use Ant to compile the code; see the README.txt file for help on configuring the build.
Deploying a filter
To add a filter to a web application, you must first put the compiled filter class in the web application's classpath, which is normally done by putting it under WEB-INF/classes or in a jar file in WEB-INF/lib. The filter is then added to the WEB-INF/web.xml configuration file in much the same way a servlet is, in that there are two configuration blocks. The first defines the filter and gives it a name, and the second defines the circumstances in which the filter is invoked.
The configuration block
The filter class is defined with a block, which takes the following child elements:
filter-name The name which will be used to identify the filter elsewhere in the web.xml file.
filter-class The classname, including package, of the filter. This name will be used by the servlet container to load the filter class.
init-param Initialization parameters to pass to the filter. We'll discuss these shortly.
description Long description for the filter, this may be used by configuration tools also.
icon Optional paths to image files for GUI configuration tools to use to represent the filter.
display-name Optional descriptive text for the filter, mainly useful for configuration tools.
The only required elements are the name and class; the icon and display-name are pointless unless you're using a tool which uses them. Here is the configuration for the TimerFilter.

Timer
com.kief.FilterDemo.TimerFilter

This filter times the execution of the request after
the filter itself, and prints the execution time to
the standard output.


Note that the same filter class can be defined in multiple blocks, each with a different name. This creates a separate instance of the class for each block, each of which can have different configuration parameters

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.