Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
1
UNIT-V Servlets
The Life Cycle of a Servlet
Using Tomcat for Servlet Development
Create and Compile the Servlet Source Code
Start Tomcat
Start a Web Browser and Request the Servlet
The Servlet API
The Javax.Servlet Package
The javax.Servlet.http Package.
2
Application Container
J2EE Architecture Client Tier
Applet Container
Applet
Application Container
Application
JDBC
JAXP
JAAS
J M S
ClientApp (JAR file)
Main AppClass
Public static void main (String args[ ] )
Java Packages,
Classes, Libraries
Deplo
ym
ent
Descrip
tor
• Client Container has a contract with applications to provide certain functionality to the components in the application
Cont..
Introduction
• Java networking capabilities
– Socket-based and packet-based communications
• Package java.net
– Remote Method Invocation (RMI)
• Package java.rmi
– Servlets and Java Server Pages (JSP)
• Request-response model
• Packages javax.servlet
javax.servlet.http
javax.servlet.jsp
javax.servlet.tagext
• Form the Web tier of J2EE
3
Introduction to Java Servlet
• Servlets are the basic building blocks for building web-based interfaces to applications.
• The Servlet technology provides a common programming model that is also the foundation for Java Server Pages.
• A Servlet component can delegate the requests to its back-end tier such as a database management system, RMI, EAI, or other Enterprise Information System (EIS).
• A Servlet is deployed as a middle tier just like other web components such as JSP components.
• The Servlet components are building block components, which always work together with other components such as JSP components, JavaBean components, Enterprise Java Bean (EJB) components, and web service components.
• A Servlet component is also a distributed component, which can provide services to remote clients and also access remote resources.
4
• The Java Servlet is a server-side web component that takes
a HTTP request from a client, handles it, talks to a database,
talks to a JavaBean component, and responds with a HTTP
response or dispatches the request to other Servlets or JSP
components.
• Servlets can dynamically produce text-based HTML markup
contents and binary contents as well contents based on the
client’s request.
Cont..
5
Java Servlet Advantages
• Efficiency: Reduction of the time need for creating new
processes and initialization and reduction of memory
requirements as well.
• Convenience: All needed functionality is provided by the
Servlet API.
• Portability: Cross-platform, Write Once Run Anywhere
(WORA) code.
• Security: Built-in security layers.
• Open source: Free Servlet development kits available for
download.
• Functionality: Session tracking, data sharing, JDBC
database connections, etc.
Cont..
6
Support Environments for Java Servlets
• A Java Servlet application is supported by its Servlet container.
• The Apache Tomcat web server is the official reference implementation of Servlet containers, supporting Servlets and JSP.
• Java Servlet API includes two packages:
javax.servlet
javax.servlet.http
• javax.servlet package has two sub-packages for JSP and JSP custom tags
javax.servlet.jsp
javax.servlet.tagext
• The classes and interfaces in the javax.servlet package are protocol-independent where as of javax.servlet.http are specific to HTTP.
Cont..
7
Note: The continuous arrows depict associations, while broken arrows indicate dependencies. An association could be in inheritance, composition, or even navigability.
8
javax.servlet
Cont..
9
Purpose Class/Interface
Servlet Implementation javax.servlet.Servlet
javax.servlet.SingleThreadModel
javax.servlet.GenericServlet
javax.servlet.http.HttpServlet
Servlet Configuration javax.servlet.ServletConfig
Servlet Exceptions javax.servlet.ServletException
javax.servlet.UnavailableException
Requests and Responses javax.servlet.http.HttpServleRequest
javax.servlet.http.HttpServleResponse
javax.servlet.ServletInputStream
javax.servlet.ServletOutputStream
javax.servlet.ServletRequest
javax.servlet.ServletResponse
Session Tracking javax.servlet.http.HttpSession
javax.servlet.http.HttpSessionBindingListener
javax.servlet.http.HttpSessionBindingEvent
Servlet Context Javax.servlet.ServletContext
Cont..
10
Servlet Implementation Servlet implementation can be done in 3 ways:
1. Servlet Interface
2. GenericServlet
3. HttpServlet
The Servlet Interface public interface Servlet Note: The interface specifies the contract between the web container and a Servlet.
11
Interface Servlet and the Servlet Life Cycle
• Interface Servlet
– All servlets must implement this interface
– All methods of interface Servlet are invoked by servlet container
• Servlet life cycle
• A Servlet has a lifecycle just like a Java applet. The lifecycle is managed by the Servlet container.
• There are three methods in the Servlet interface, which each Servlet class must implement.
• They are init(), service(), and destroy().
– Servlet container invokes the servlet’s init method
– Servlet’s service method handles requests
– Servlet’s destroy method releases servlet resources when the servlet container terminates the servlet
• Servlet implementation
– GenericServlet
– HttpServlet
Cont..
12
Java Servlet Architecture
• A Java Servlet is a typical Java class that extends the
abstract class HttpServlet.
• The HttpServlet class extends another abstract class called
GenericServlet.
• The GenericServlet class implements three interfaces:
javax.servlet.Servlet
javax.servlet.ServletConfig and
java.io.Serializable.
Cont..
13
Java Servlet Class Hierarchy Cont..
14
The Lifecycle of a Servlet Cont..
15
Method Description
void init( ServletConfig config ) throws ServletException
The servlet container calls this method once during a servlet’s execution cycle to initialize the servlet. The ServletConfig argument is supplied by the servlet container that executes the servlet.
ServletConfig
getServletConfig()
This method returns a reference to an object that
implements interface ServletConfig. This object provides access to the servlet’s configuration information such as servlet initialization parameters and the servlet’s ServletContext, which provides the servlet with access to its environment (i.e., the servlet container in which the servlet executes).
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 ) throws ServletException, IOException
The servlet container calls this method to respond to a client request to the servlet.
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 deallocated here.
Fig. Methods of interface Servlet (package javax.servlet).
Javax.servlet.Servlet interface, the following five methods must be implemented: Cont..
16
Cont..
17
The HttpServlet Class
18
javax.servlet.http
public abstract class HttpServlet extends GenericServlet implements Serializable The methods are:
• public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
• protected void service(HttpServletRequest request, HttpServletResponse response)
• protected void doGet(HttpServletRequest request, HttpServletResponse response)
• protected void doPost(HttpServletRequest request, HttpServletResponse response)
• protected void doHead(HttpServletRequest request, HttpServletResponse response)
• protected void doDelete(HttpServletRequest request, HttpServletResponse response)
• protected void doOptions(HttpServletRequest request, HttpServletResponse response)
• protected void doPut(HttpServletRequest request, HttpServletResponse response)
• protected void doTrace(HttpServletRequest request, HttpServletResponse response)
• protected long getLastModified(HttpServletRequest request)
Cont..
19
Processing of HTTP Requests and Responses
• public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
• protected void service(HttpServletRequest request, HttpServletResponse response)
• Overrides method service
• HttpServlet implements this method to be a dispatcherof HTTP requests.
• Two most common HTTP request types
– get requests
– post requests
• Method doGet responds to get requests
• Method doPost responds to post requests
• HttpServletRequest and HttpServletResponse objects
Cont..
20
The prototypes of doGet() and doPost()
• void doGet( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException;
• void doPost( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException;
• HttpServletRequest and HttpServletResponse are the two interfaces that provide the Servlet with full access to all information from the request and the response sent back to the client.
• When the doGet() or doPost() is called, the Servlet container passes in the HttpServletRequest and HttpServletResponse objects.
Cont..
21
The sequence of method calls when the container receives a request for a servlet is: The container calls the public service() method.
The public service() method calls the protected service()
method after casting the arguments to HttpServletRequest and HttpServletResponse respectively.
The protected service() method calls one of the doXXX() methods, depending on the type of the HTTP request method.
Cont..
22
HttpServlet Class - Methods
Method Description
doDelete Called in response to an HTTP delete request. Such a request is
normally used to delete a file from a server. This may not be available
on some servers, because of its inherent security risks (e.g., the client
could delete a file that is critical to the execution of the server or an
application).
doHead Called in response to an HTTP head request. Such a request is normally
used when the client only wants the headers of a response, such as the
content type and content length of the response.
doOptions Called in response to an HTTP options request. This returns information to the client indicating the HTTP options supported by the server, such
as the version of HTTP (1.0 or 1.1) and the request methods the server
supports.
doPut Called in response to an HTTP put request. Such a request is normally
used to store a file on the server. This may not be available on some
servers, because of its inherent security risks (e.g., the client could
place an executable application on the server, which, if executed, could
damage the server—perhaps by deleting critical files or occupying
resources).
doTrace Called in response to an HTTP trace request. Such a request is normally
used for debugging. The implementation of this method automatically
returns an HTML document to the client containing the request header information (data sent by the browser as part of the request).
Fig. Other methods of class HttpServlet.
Cont..
23
Web Server Configuration/ Servlet Configuration
• In the Java Servlet API, javax.servlet.ServletConfig objects represent the configuration of a servlet.
• The configuration information contains initialization parameters (a set of name/value pairs), the name of the servlet and a javax.servlet.ServletContext object, which gives the servlet information about the container.
• The initialization parameters and the name of a servlet can be specified in the deployment descriptor (the web.xml file).
24
Example:
<web-app>
<servlet>
<servlet-name> Servlet1</servlet-name>
<servlet-class>SimpleServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/s1/*</url-pattern>
</servlet-mapping>
</servlet>
</web-app>
Cont..
25
26
Servlet Exception
javax.servlet package specifies two exception classes:
• javax.servlet.ServletException
• javax.servlet.UnavailableException
• public class ServletException extends java.lang.Exception
This is a generic exception, which can be thrown by the init(),
service(), doXXX(), and destroy() methods. The class provides the
following constructions:
• public ServletException()
• public ServletException(String message)
While creating objects of type ServletException, you can embed
any application level exception (called the root-cause).
27
The containers use the root-cause exception for logging purposes.
For instance, you can embed a java.sql.SQLException in a
javax.servlet.ServletException. There are two additional
constructors to support root-cause exceptions:
• public ServletException(Throwable cause)
• public ServletException(String message, Throwable
cause)
The getRootCause() returns the root-cause exception:
• public Throwable getRootCause()
• public class UnavailableException extends
ServletException
The purpose of this is to indicate to the webcontainer that the
servlet is either temporarily or permanently unavailable, then the
following constructions:
• public UnavailableException(String message)
• public UnavailableException(String message, int
seconds)
Cont..
28
Examples on Servlet
Basic Directory Structure
webapps | ---- servlet/rollno | ---- *.html, *.jsp | ---- WEB-INF | ---- web.xml | ---- classes | ---- *.java | ---- *.class
To connect servlet-java, set path= C:\Program Files\Apache Software Foundation\Tomcat XX\common\ lib\servlet-api
Write web.xml file
29
Directory Description
context root This is the root directory for the Web application. All the JSPs, HTML documents, servlets and supporting files such as images and class files reside in this directory or its subdirectories. The name of this directory is specified by the Web application creator. To provide structure in a
Web application, subdirectories can be placed in the context root. For example, if your application uses many images, you might place an images subdirectory in this directory. The examples of this chapter use jhtp5 as the context root.
WEB-INF This directory contains the Web application deployment descriptor (web.xml).
WEB-INF/classes This directory contains the servlet class files and other
supporting class files used in a Web application. If the classes are part of a package, the complete package directory structure would begin here.
WEB-INF/lib This directory contains Java archive (JAR) files. The JAR files can contain servlet class files and other supporting class files used in a Web application. Fig. Web application standard directories.
Cont..
30
Example-1
import java.io.*; import javax.servlet.*; public class SimpleServlet extends GenericServlet{ public void init() throws ServletException { System.out.println("Servlet has Instantiated"); } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw=response.getWriter(); pw.println("Service method is called"); } public void destroy() { System.out.println("Servlet has destroyed"); } }
SimpleServlet.java
31
<web-app> <!–- Servlet Definition-
<servlet> <servlet-name> Servlet1</servlet-name> <servlet-class>SimpleServlet</servlet-class> </servlet> <!–- Servlet Mapping -
<servlet-mapping> <servlet-name>Servlet1</servlet-name> <url-pattern>/s1/*</url-pattern> </servlet-mapping> </web-app>
web.xml Cont..
32
• Compile SimpleServlet.java
• Start Tomcat
• Open any browser, type: localhost:8080/kkbservelets/s1
Steps to run any Servlet program
Cont..