Search This Blog

Showing posts with label J2EE. Show all posts
Showing posts with label J2EE. Show all posts
Tuesday, 8 November 2011

Basic Architecture of a Servlet!

0 comments

THE BASIC SERVLET ARCHITECTURE! 
         
          A Servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of that interface, namely javax.servlet.GenericServlet and javax.servlet.http.HttpServlet. The set of all classes and interfaces required for developing and running a Servlet is called Servlet API.

The Servlet API is a part of the Servlet specification designed by Sun Microsystems. This API is supported by all Servlet containers, such as Tomcat and Weblogic. The API contains classes and interfaces that define a standard contract between the Servlet class and Servlet container (or Servlet engine). These classes and interfaces are packaged in the following two packages of the Servlet API:
  • javax.servlet &
  • javax.servlet.http
These packages contain classes and interfaces that allow the Servlet to access the basic services provided by the Servlet container. The javax.servlet package contains classes and interfaces to support generic, protocol-independent Servlet. These classes are extended by the classes in javax.servlet.http package to add HTTP-specific functionality.
Every Servlet must implement the javax.servlet.Servlet interface. Most servlets implement this interface by extending one of the two special classes given below:
  • javax.servlet.GenericServlet
  • javax.servlet.http.HTTPServlet
HTTPServlet is a sub class of GenericServlet super class and adds HTTP functionality to a Servlet.
Servlet - The Root Interface of Servlets
Architecturally, all servlets must implement the Servlet interface of package javax.servlet. It provides five methods, which are executed automatically by the web server. There is no main() method in a servlet just like an applet. The methods described in this interface are as follows:
Method
Description
void init(servletConfig config)
This method is automatically called once during a servlet’s execution cycle to initialize the servlet.
ServletConfig getServletConfig()
This method returns a reference to the object that implements the interface ServletConfig. It provides access to the servlet’s configuration information.
String getServletInfo()
This method is defined by a servlet programmer to return a string containing servlet information such as the servlet’s author and version.
void Service(ServletRequest request, ServletResponse response)
This method is called one or more times by the server to respond based on the number of requests made by the clients simultaneously.
void destroy()
This “cleanup” method is called when a servlet is terminated by its servlet container. Resources used by the servlet, such as an open file or an open database connection should be de-allocated here.

A servlet’s life cycle begins when the servlet container loads the servlet into memory – normally, in response to the first request that the servlet receives. Before the servlet can handle the request, the servlet container invokes the servlet’s init method for initializing the servlet's variables and resources. Then the servlet’s service() method is called as a response to the client’s request.
All requests are handled by the servlet’s service method, which receives the request, processes the request, and sends a response to the client in the form of html. During the servlet’s life time, method service is called one per request. Each new request typically results in a new thread of execution (created by the servlet container) in which method service gets executed. When the servlet container terminates the servlet, the servlet’s destroy method is called to release servlet resources.
Contents of javax.servlet Package:
The classes and interfaces defined in the javax.servlet package are listed below. The Servlet container provides the implementation of these classes and interfaces.
Interfaces: Servlet, RequestDispatcher, ServletConfig, ServletContext, ServletContextListener, ServletRequest, ServletResponse, SingleThreadModel, Filter, FilterChain, FilterConfig, ServletContextAttributeListener, ServletRequestAttributeListener, SerlvetRequestListener
Classes: ServletContextEvent, ServletInputStream, ServletOutputStream, ServletRequestWrapper, ServletResponseWrapper, GenericServlet, ServletContextAttributeEvent, ServletRequestAttributeEvent, ServletRequestEvent, ServletException, UnavailableException
Contents of javax.servlet.http Package:
The javax.servlet.http package supports the development of Servlets that make use of HTTP protocol. The classes in this package extend the Servlet functionality to support HTTP specific features that include request and response headers, support for different request methods and cookies. The classes and interfaces defined in javax.servlet.http package are given below:
Type
Name
Description
Interface HttpServletRequest Extends the ServletRequest interface to provide request information for HTTP servlets
Interface HttpServletResponse Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response
Interface HTTPSession Provides a way to identify the user across more than one page request or visit to a website and store the information about the user
Interface HttpSessionBindingListener Causes an object to be notified when it is bound to or unbound from a session.
Class Cookie Creates a cookie, a small amount of information sent by a Servlet to a web browser, saved by the browser, and later sent back to the server
Class HttpServlet Provides an abstract class to be sub classed to create an HTTP Servlet suitable for a website.
Class HttpSessionBindingEvent Sent to an object that implements HttpSessionBindingListener when the object is bound to or unbound from the session.
Class HttpUtils Provides a collection of methods that are useful in writing HTTP servlets


Continue reading →
Friday, 28 October 2011

Standard Actions in JSP!

0 comments
JSP STANDARD ACTIONS! 
Standard actions are special tags provided in JSP for performing some of the most common tasks in a JSP program, such as including content from other resources, forwarding requests to other resources and interacting with Java Beans. JSP containers process actions at request time.
Actions are delimited by <jsp:action> and </jsp:action> tags, where action is one of the standard actions defined in JSP as listed below:

<jsp:include> Action:
This action enables dynamic content to be included in a Java Server Page. It just copies the content of the resource into the JSP once, at JSP translation time. If the included resource changes between requests, the next request to the JSP containing the <jsp:include> action includes the new content of the resource.
There are two attributes for this action include for specifying more about this action. They are listed below:


Attribute
Description
page
Specifies the relative URI path of the resource to include. The resource must be part of the same web application.
flush
Specifies whether the buffer should be flushed after the “include” is performed. In JSP1.1. this attribute is required to be true.

Table: Attributes of ‘include’ action with their description
The following is a JSP program (include.jsp) that includes two HTML and one JSP resources to generate static and dynamic content of a web page as a response:
<? xml version = “1.0”>
<html>
<head><title> JSP demonstrating ‘include’ action </title>
</head>
<body>
<table>
<tr>
<td style = “background-color : black;”>
<jsp:include page = “banner.html” flush = “true” />
</td>
</tr>
<tr>
<td style = width : 160px”>
<jsp:include page = “toc.html” flush = “true” />
</td>
<td style = “vertical-align : top”>
<jsp:include page = clock.jsp” flush = “true” />
</td>
</tr>
</table>
</body>
</html>
<jsp:forward> Action:
This action enables a JSP to forward request processing to a different resource. Request processing by the original JSP terminates as soon as the JSP forwards the request. This action has only one attribute: page that specifies the relative URI of the resource (in the same web application) to which the request should be forwarded.
The following is a JSP (forward.jsp) file that gets the user input – first name and forwards it to another JSP (clock.jsp) that displays the name and a clock:
<?xml version = “1.0”>
<head> <title> Forward request JSP </title>
</head>
<body>
<%
String name = request.getParameter(“fname”);
if (name != null)
{
%>
<jsp:forward page = “clock.jsp”>
<jsp:param name=“date”
value =“<%= new.java.util.Date() %>” />

</jsp:forward>
<%
}
Else {
%>
<form action = “forward.jsp” method = “get”>
<p>Type your first name and press Submit</p>
<p> <input type = “text” name = “fname” />
<input type = “submit” value = “Submit” />
</p>
</form>
<%
}
%>
</body>
</html>
Program: Forward.jsp that gets the user name and forwards it to another JSP

<?xml version = “1.0”>
<head> <title> Processing a forward request </title>
</head>
<body>
<h1>
Hello <%= request.getParameter(“fname”) %> <br/>
Your request has been received and forwarded!
</h1>
<table style= “border : 6px outset;”>
<tr>
<td style= “background-color : black;”>
<h2>
<%= request.getParameter(“date”) %>
</h2>
</td>
</tr>
</table>
</body>
</html>
Program: Clock.jsp that gets the gets name and date and displays them

In the above JSP example forward.jsp, when the user enters his name and presses submit button, his request is processed to get the current date and time of the server using java.lang.Date() object. Then the date and time are forwarded to another JSP as a parameter using jsp:param and jsp:forward actions, where the date and time of the server are displayed along with the name of the user.
The jsp:param action specifies name/value pair of information that are passed to the <jsp:include>, <jsp:forward> and <jsp:plugin> actions. Every <jsp:param> action has two required attributes: name and value. If a <jsp:action> specifies a parameter that already exists, the new value for the parameter takes precedence over the original value. All values for that parameter can be obtained by using JSP implicit object request’s getParameterValues method, which returns an array of strings.
Continue reading →

Server-side Scripting using JSP!

1 comments
SERVER-SIDE SCRIPTING USING JSP!
JSP often present dynamically generated content as part of an HTML document sent to the client in response to a request. In some cases, the content is static, but is output only if certain conditions are met during a request. JSP programmers can insert Java code and logic in a JSP using script.
Scripting Components:
JSP scripting components include: scriptlets, comments, expressions, declarations and escape sequence characters. Scriptlets are blocks of code delimited by <% and %>. They contain Java statements that the container places in method –jspService at translation time.
JSPs supports three comment styles: JSP comments, HTML comments and comments from the scripting language like JavaScript. JSP comments are delimited by <%-- and --%>. HTML comments are delimited with <!-- and -->. Scripting language comments are Java comments and are delimited by / and /. JSP comments and scripting-language comments are ignored and do not appear in the response to a client.
A JSP expression, delimited by <%= and %> contains Java code that is evaluated when a client requests the JSP containing the expression. The container converts the result of a JSP expression to a String object, and then outputs the string as part of the response to the client.
Declarations (delimited by <%! and %>) enable a JSP programmer to define variables and methods. The variables become instance variables of the Servlet class and the methods become members. Declarations of variables and methods in a JSP use Java syntax. Hence, declaring a variable without using a semicolon is a syntax error.
Escape sequences are sequence of characters used in JSP to make use of the special characters like <% and %> as part of the output. The escape sequences are as follows:
<\% %\> \’ \” \\
The following is an example for JSP code written using two of the JSP components - scriptlets and expression:
<? xml version = “1.0”>
<html>
<head>
<title> Processing “get” request with data </title>
</head>
<body>
<%
String name = request.getParameter(“fname”);
if (name != null)
{
%>
<h1>
Hello <%= name %> <br/>
Welcome to Java Servlet Pages!
</h1>
<%
}
else {
%>
<form action = “welcome.jsp” method = “get”>
<p>Type your first name and press Submit</p>
<p> <input type = “text” name = “fname” />
<input type = “submit” value = “Submit” />
</p>
</form>
<%
}
%>
</body>
</html>
 Standard Actions:
Standard actions are special tags provided in JSP for performing some of the most common tasks in a JSP program, such as including content from other resources, forwarding requests to other resources and interacting with Java Beans. JSP containers process actions at request time.
Actions are delimited by <jsp:action> and </jsp:action> tags, where action is one of the standard actions defined in JSP as listed below:


Action
Description
<jsp:include>
Dynamically includes another resource in a JSP. As the JSP executes, the referenced resource is included and processed.
<jsp:forward>
Forwards request processing to another JSP, servlet or static page. This action terminates the current JSP’s execution.
<jsp:plugin>
Allows a plug-in component to be added to a page in the form of a browser-specific object or embed HTML element.
<jsp:param>
Used with the include, forward and plug-in actions to specify additional name/value pairs of information for use by these actions.
JavaBean Manipulation
<jsp:useBean>
Specifies that the JSP uses a JavaBean instance. This action specifies the scope of the bean and assigns it an ID that scripting components can use to manipulate the bean.
<jsp:setProperty>
Sets the property in the specified JavaBean instance.
<jsp:getProperty>
Gets a property in the specified JavaBean instance and converts the result to a String for output in the response.

Table: JSP actions and their description
Continue reading →
Saturday, 22 October 2011

Introduction to Java Server Pages

0 comments
JAVA SERVER PAGES! 
Java Server Pages (JSP) is an extension of Servlet technology that simplifies the delivery of dynamic web content. It provides a set of predefined components for the web application programmers to develop server side scripts that can generate dynamic web pages. In addition to the packages javax.servlet and javax.servlet.http containing classes and interfaces for Servlet programmers, Java provides two packages for JSP programming:
  • javax.servlet.jsp &
  • javax.servlet.jsp.tagext
To run JSP, we need to have a web server that supports JSP and also the packages jsp and jsp.tagext, which are part of the Java Servlet API.
In many ways, Java Server Pages look like standard HTML and XML documents. In fact, they normally include HTML or XML markup. Such markup is known as fixed-template data or fixed-template text. JSP programmers can reuse Java Beans and create custom tag libraries that encapsulate complex, dynamic functionality.
Programmers tend to use JSP when most of the content sent to the client is fixed template data and only a small portion of the content is generated dynamically with Java code. On the other hand, Servlets are preferred only when a small portion of the content sent to the client is fixed-template data. In most cases, servlet and JSP are interchangeable.
As with servlets, JSPs normally execute as part of a Web Server, which acts as a container to JSP. When a JSP-enabled server receives the first request for a JSP, the JSP container translates that JSP into a Java servlet that handles the current request and the future requests to the JSP.
The request and response mechanism and life cycle of a JSP are the same as that of a servlet. JSPs can define methods jspInit and jspDestroy (similar to servlet methods init and destroy), which the JSP container invokes when initializing a JSP, and terminating a JSP respectively.
A simple JSP program that displays the current time of the server is as follows:
<?xml version = “1.0”>
<head>
<meta http-equiv = “refresh” content = “60” />
<title> A simple JSP Clock </title>
<style>
.big {font-family : Helvetica, arial, sans-serif;
Font-weight: bold; font-size : 2em;}
</style>
</head>
<body>
<p class = “big”> Simple JSP Example </p>
<table style= “border : 6px outset;”>
<tr>
<td style= “background-color : black;”>
<p class = “big” style = “color : cyan;”>
<%= new java.util.Date() %>
</p>
</td>
</tr>
</table>
</body>
</html>
In this example, JSP is composed of HTML tags and Java code. The HTML tags define the web page, which would be sent normally as a response to a client’s request. Apart from HTML tags, there is only one line of java code that retrieves the current data and time of the server and includes it as part of the web page. The code is as follows:
<%= new java.util.Date() %>
This line of code is a JSP expression and is delimited by <%= and %>. This line of code creates a new instance of class Date from the package java.util to get the current time and date from the server. To return the result as part of the web content we use = (equal) sign which calls the response object’s write method. Therefore, the above line of code is equivalent to the following statement:
<% response.write( new java.util.Date() ) %>
The JSP container converts the result of every JSP expression into a string that is output as part of the response to the client. In the above example, there is an HTML tag with the meta element. This element is used to set a refresh interval of 60 seconds for the document. This causes the browser to request clock.jsp every 60 seconds, so that the date and time are updated every minute with the current date and time of the server.
Implicit Objects:
Implicit objects are objects provided in JSP for having access to many Servlet capabilities in the context of a Java Server Page. Implicit objects have four scopes: Application, Page, Request and Session. The objects having the application scope can be used by both JSP and Servlet used in a web application. Objects with page scope exist only in the page that defines them.
Objects with request scope exist for the duration of the request. For e.g., a JSP can partially process a request, then forward the request to another Servlet or JSP for further processing. Request-scope objects go out of scope when request processing completes with a response to the client. Objects with session scope exist for the client’s entire browsing session.
Many of the implicit objects extend the classes that implement interfaces provided in the Servlet API. Thus, JSP can use the same methods that a Servlet use to interact with such objects. The implicit JSP objects and their description are as follows:
Implicit Objects
Description
Application scope
application
This is an instance of javax.servlet.ServletContext class. It acts as a container in which JSP executes.
Page scope Objects
config
This is an object of javax.servlet.ServletConfig class. It represents the JSP configuration options.
exception
This is an instance of java.lang.Throwable class. It represents the exception that is passed to the JSP error page.
out
It is an instance of javax.servlet.jsp.JspWriter class. It writes text as part of the response to a request. It is used implicitly with JSP expressions and actions that insert String content in a response.
page
This javax.lang.Object represents a reference for the current JSP instance.
pageContext
This javax.servlet.jsp.PageContext object hides the implementation details of the underlying Servlet and JSP container and provides JSP programmers with access to the implicit objects.
response
This object is an instance of a class that implements HTTPServletResponse of javax.servlet.http package. It represents the response to the client.
Request scope
request
This object is an instance of a class that implements HTTPServletRequest of javax.servlet.http package. It represents the client request.
Session scope
session
This is an instance of the class javax.servlet.http.HTTPSession and represents the client session information if such a session has been created.
Table: Implicit JSP Objects with their description
Continue reading →

Introduction to Java Servlets

0 comments
JAVA SERVLETS! 
Servlets are server-side Java programs that are loaded and executed by an Application Server like Apache Tomcat. A servlet can be considered as server-side applet that accepts requests from a client (via the Web Server), performs some task, and returns the result. The following figure depicts the role of a Servlet in a web application:

Fig. : Interaction between a Client and a Servlet on the Web Server

The following is a list of interactions that take place between a web client and a Servlet (server):
  1. The client (Web Browser) makes a request via HTTP
  2. The Web Server (or Application Server) receives the request and forwards it to the Servlet. If the Servlet has not yet been loaded, the Web Server will load it on the Java Virtual Machine and execute it.
  3. The Servlet that receives the HTTP request will process the request by running the script provided in the servlet
  4. The Servlet will return a response back to the Web Server in the form of a web page (html file).
  5. The Web Server will forward the response to the client.
Servlet technology is used to create dynamic web pages by writing programs in Java that are executed on a server.  Servlets are designed to handle HTTP requests - GET, and POST.  They can run on any Java-enabled platform having an application server.

What are the advantages of Servlets over other server-side technologies used for dynamic web pages?
The advantages of Servlets over Common Gateway Interface (CGI), a standard defined for running application code on the server, are as follows:
  1. Servlets run faster than CGI.
  2. Servlets are platform independent as they  are written in Java, which is platform independent. Servlets can run on any Servlet enabled web server.
  3. Servlets make use of a standard vendor independent API supported by many web servers. Moreover, the API used by  Servlets posses the features of Java, such as platform independence and portability.
  4. Using Servlets removes the overhead of creating a new process for each client, as Servlet does not run a separate process for each request made by a client. There will be only one instance of a Servlet that can handle all requests made by the clients concurrently.
Servlet Container:
Servlet container, also known as Servlet engine, is a component of Server software like Tomcat Apache that provides the runtime environment for Servlets. The services provided by the Servlet container are as follows:
  • Network services: The Servlet container is responsible for loading a Servlet into memory. The loading may be done from a local file system, a remote file system, or other network services. Moreover, the Servlet container provides network services over which the request and response between the Servlet and its clients are carried out.
  • Decode and Encode MIME based messages: The Servlet container provides the service of decoding and encoding MIME based messages. 
  • Manage Servlet life-cycle: The Servlet container manages the lifecycle of a Servlet 
  • Resource Management: The Servlet container manages the files required for generating static and dynamic web pages, such as HTML files, Servlets, and JSP pages.
  • Security service: The Servlet container handles authorization and authentication of resources available on the server.
  • Session Management: The Servlet container maintains a session by appending a session ID to the URL path.
Servlet container makes use of HTTP as the protocol for receiving request and sending response to its clients; however, additional protocols, such as HTTPS (HTTP over SSL) may be supported based on the requirement.


The Servlet API:
Servlet API refers to the set of packages provided by Sun Microsystems for the development of Servlet programs. In addition to these packages, we need an Application Server such as Apache Tomcat or Internet Information Server (IIS) that act as a container or runner for the Servlet. 
 All web servers that support Servlet must have Servlet API for the creation and running of Servlets.  Servlet API consists of the following two packages:
  • javax.servlet &
  • javax.servlet.http
These packages contain classes and interfaces that can be used by a Servlet for its development. The javax.servlet package contains classes and interfaces to support generic, protocol-independent Servlet. These classes are extended by the classes in javax.servlet.http package to add HTTP-specific functionality in them.

          A Servlet, in its most general form, is an instance of a class which implements the javax.servlet.Servlet interface. Most Servlets, however, extend one of the standard implementations of that interface - javax.servlet.GenericServlet or javax.servlet.http.HttpServlet

The various stages of a Servlet created using javax.servlet.http.HttpServlet class is also called servlet life cycle, which includes three stages namely  initialization (loading), running (servicing) and unloading (terminating).

Servlet Life Cycle:

In order to initialize a Servlet, the following steps are followed by the servlet container:
  1. Servlet container loads the Servlet class (and probably other classes which are referenced by the Servlet) and creates an instance of it by calling the no-args constructor. 
  2. Servlet container calls the Servlet's init(ServletConfig config) method, which contains the code for performing one-time setup of Servlet.  
  3. Servlet container also creates the ServletConfig object so that the configuration details can be retrieved later by calling the Servlet's getServletConfig() method.

    Servlets which extend GenericServlet (or its subclass HttpServlet) should call super.init(config) at the beginning of the init method to make use of configuration object. The ServletConfig object contains Servlet parameters and a reference to the Servlet's ServletContext. The init method is guaranteed to be called only once during the Servlet's lifecycle. Hence, it does not need to be thread-safe because the service method will not be called until the call to init returns.
          
        Once the Servlet is initialized, its service(ServletRequest req, ServletResponse res) method will be called for every request made by the client  to the Servlet. This method may be called concurrently (i.e. multiple threads may call this method at the same time) so it should be implemented in a thread-safe manner.

          When the Servlet needs to be unloaded (e.g. because a new version should be loaded or the server is shutting down) the destroy() method is called. There may still be threads that execute the service method when destroy is called, so destroy has to be thread-safe. All resources which were allocated in init should be released in destroy. This method like init  is guaranteed to be called only once during the Servlet's lifecycle.
Continue reading →