Вы находитесь на странице: 1из 23

Servlet

Introduction In the early days, web servers deliver static contents that are indifferent to users' requests. Java servlets are server-side programs (running inside a web server) that handle clients' requests and return a customized or dynamic response for each request. The dynamic response could be based on user's input (e.g., search, online shopping, online transaction) with data retrieved from databases or other applications, or time-sensitive data (such as news and stock prices). Servlets provide a component-based, platform-independent method for building Web-based applications, without the performance limitations of CGI programs. Servlets have access to the entire family of Java APIs, including the JDBC API to access enterprise databases. Java servlets typically run on the HTTP protocol. HTTP is an asymmetrical request-response protocol. The client sends a request message to the server, and the server returns a response message as illustrated.

What are Servlets? Java Servlets are programs that run on a Web or Application server and act as a middle layer between a requests coming from a Web browser or other HTTP client and databases or applications on the HTTP server.Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically.

Java Servlets often serve the same purpose as programs implemented using the Common Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create a separate process to handle each client request. Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already. What is web application? A web application is an application accessible from the web. A web application is composed of web components like Servlet, JSP, Filter etc. and other components such as HTML. The web components typically execute in Web Server and respond to HTTP request. CGI CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request. For each request, it starts a new process.

Disadvantages of CGI 1. If number of clients increases, it takes more time for sending response.

2. For each request, it starts a process and Web server is limited to start processes. 3. It uses platform dependent language e.g. C, C++, perL Advantage of Servlet

There are many advantages of servlet over CGI. The web container creates threads for handling the multiple requests to the servlet. Threads have a lot of benefits over the processes such as they share a common memory area, lightweight, cost of communication between the threads are low. The basic benefits of servlets are as follows. Better performance : because it create a thread for each request not process Portability : because it uses java language Robust: servlets are managed by JVM so no need to worry about memory leak, garbage collection, etc., Secure: since it uses Java

Servlet Architecture:
Following diagram shows the position of Servelts in a Web Application.

Servlets Tasks:

Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web page or it could also come from an applet or a custom HTTP client program. Read the implicit HTTP request data sent by the clients (browsers). This includes cookies, media types and compression schemes the browser understands, and so forth. Process the data and generate the results. This process may require talking to a database, executing an RMI or CORBA call, invoking a Web service, or computing the response directly. Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc. Send the implicit HTTP response to the clients (browsers). This includes telling the browsers or other clients what type of document is being returned (e.g., HTML), setting cookies and caching parameters, and other such tasks. There are some key points that must be known by the servlet programmer. Let's first briefly discuss these points before starting the servlet. These are: 1. HTTP 2. HTTP Request Types 3. Difference between Get and Post method 4. Container 5. Server

6. Difference between web server and application server 7. Content Type 8. Introduction of XML 9. Deployment 1. HTTP (Hyper Text Transfer Protocol) Http is the protocol that allows web servers and browsers to exchange data over the web.It is a request response protocol.Http uses reliable TCP connections bydefault on TCP port 80.

Http Request Methods: Every request has a header that tells the status of the client. There are many request methods. Get and Post requests are mostly used. The http request methods are: GET POST HEAD PUT DELETE OPTIONS TRACE

Difference between Get and Post methods

Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api. Servlet Interface Servlet interface provides common behavior to all theservlets.Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It provides 3life cycle methods that are used to initialize the servlet, to service the requests, and to destroy the servlet and 2 non-life cycle methods.

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods of servlet.These are invoked by the web container. 1. public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and invoked by the web container only once. 2. public void service(ServletRequest request,ServletResponse response) provides response for the incoming request. It is invoked at each request by the web container. 3. public void destroy() is invoked only once and indicates that servlet is being destroyed. 4. public ServletConfig getServletConfig() returns the object of ServletConfig. 5. public String getServletInfo() returns information about servlet such as writer, copyright, versionetc. GenericServlet class GenericServlet class implements Servlet,ServletConfig and Serializable interfaces. It providesthe implementation of all the methods of these interfaces except the service method.GenericServlet class can handle any type of request so it is protocol-independent.You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service method. There are many methods in GenericServlet class. They are as follows: 1. public void init(ServletConfig config) is used to initialize the servlet. 2. public abstract void service(ServletRequest request, ServletResponse response) provides service for the incoming request. It is invoked at each time when user requests for a servlet. 3. public void destroy() is invoked only once throughout the life cycle and indicates that servlet is being destroyed. 4. public ServletConfig getServletConfig() returns the object of ServletConfig.

5. public String getServletInfo() returns information about servlet such as writer, copyright, version etc. HttpServlet class The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific methods such as doGet, doPost, doHead, doTrace etc. There are many methods in HttpServlet class. They are as follows: 1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service method by converting the request and response object into http type. 2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service method, and dispatches the request to the doXXX() method depending on the incoming http request type. 3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked by the web container. 4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is invoked by the web container. 5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is invoked by the web container. 6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It is invoked by the web container.

GET method: The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ?character as follows: http://www.test.com/hello?key1=value1&key2=value2 The GET method is the default method to pass information from browser to web server and it produces a long string that appears in your browser's Location: box. Never use the GET method if you have password or other sensitive information to pass to the server. The GET method has size limitation: only 1024 characters can be in a request string. POST method: A generally more reliable method of passing information to a backend program is the POST method. This packages the information in exactly the same way as GET methods, but instead of sending it as a text string after a ?in the URL it sends it as a separate message. This message

comes to the backend program in the form of the standard input which you can parse and use for your processing. Servlet handles this type of requests using doPost() method. Reading Form Data using Servlet:Servlets handles form data parsing automatically using the following methods depending on the situation:

getParameter(): You call request.getParameter() method to get the value of a form parameter. getParameterValues(): Call this method if the parameter appears more than once and returns multiple values, for example checkbox. getParameterNames(): Call this method if you want a complete list of all parameters in the current request.

Servlet Life Cycle


A servlet life cycle can be defined as the entire process from its creation till the destruction. The following are the paths followed by a servlet

servlet class is loaded The servlet is initialized by calling the init () method. The servlet calls service () method to process a client's request. The servlet is terminated by calling the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM . The init() method : The init method is designed to be called only once. It is called when the servlet is first created, and not called again for each user request. So, it is used for one-time initializations, just as with the init method of applets.The servlet is normally created when a user first invokes a URL corresponding to the servlet, but you can also specify that the servlet be loaded when the server is first started. When a user invokes a servlet, a single instance of each servlet gets created, with each user request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method simply creates or loads some data that will be used throughout the life of the servlet.

The init method definition looks like this: public void init() throws ServletException { // Initialization code... } The service() method : The service() method is the main method to perform the actual task. The servlet container (i.e. web server) calls the service() method to handle requests coming from the client( browsers) and to write the formatted response back to the client. Each time the server receives a request for a servlet,the server spawns a new thread and calls service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate. Here is the signature of this method: public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException{ } The service () method is called by the container and service method invokes doGet, doPost, doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you override either doGet() or doPost() depending on what type of request you receive from the client. The doGet () and doPost() are most frequently used methods within each service request. Here are the signature of these two methods. The doGet() Method A GET request results from a normal request for a URL or from an HTML form that has no METHOD specified and it should be handled by doGet() method. public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code }

The doPost() Method A POST request results from an HTML form that specifically lists POST as the METHOD and it should be handled by doPost() method. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Servlet code } The destroy() method : The destroy() method is called only once at the end of the life cycle of a servlet. This method gives your servlet a chance to close database connections, halt background threads, write cookie lists or hit counts to disk, and perform other such cleanup activities. After the destroy() method is called, the servlet object is marked for garbage collection. The destroy method definition looks like this: public void destroy() { // Finalization code... } ServletRequest Interface An object of ServletRequest is used to provide theclient request information to a servlet such as contenttype, content length, parameter names and values,header information, attributes etc. Methods of ServletRequest interface There are many methods defined in the ServletRequest interface. Some of them are as follows: 1. public String getParameter(String name):is used to obtain the value of a parameter by name. 2. public String[] getParameterValues(String name):returns an array of String containing all values of given parameter name. It is mainly used to obtain values of a Multi select list box. 3. java.util.Enumeration getParameterNames(): returns an enumeration of all of the request parameter names. 4. publicint getContentLength():Returns the size of the request entity data, or -1 if not known. 5. public String getCharacterEncoding():Returns the character set encoding for the input of this

request. 6. public String getContentType():Returns the Internet Media Type of the request entity data, or null if not known. 7. public ServletInputStream getInputStream() throws IOException:Returns an input stream for reading binary data in the request body. 8. public abstract String getServerName():Returns the host name of the server that received the request. 9. publicint getServerPort():Returns the port number on which this request was received.

RequestDispatcher Interface
The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp.This interface can also be used to include the content of another resource also. It is one of the way of servlet collaboration.Thereare two methods defined in the RequestDispatcher interface. The RequestDispatcher interface provides two methods. They are: 1. public void forward(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

2. public void include(ServletRequest request,ServletResponse response)throws ServletException,java.io.IOException:Includes the content of a resource (servlet, JSP page, or HTML file) in the response.

sendRedirect() method: The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may be servlet, jsp or html file. It can accept relative URL. This method can work inside and outside the server as it uses the URL bar of the browser. Syntax of sendRedirect () method: public void sendRedirect(String URL)throws IOException;

Session Tracking
Session Tracking: Session simply means a particular interval of time. Session Tracking is a way to maintain state of an user. Http protocol is a stateless protocol. Each time user requests to the server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular user. Session Tracking Techniques

There are four techniques used in Session tracking: 1. Cookies 2. Hidden Form Field 3. URL Rewriting 4. HttpSession

1) Cookies
A cookie is a small piece of information that is persisted between the multiple client requests.Acookie has aname, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

Commonly used methods of Cookie class There are given some commonly used methods of the Cookie class. 1. public void setMaxAge(int expiry):Sets the maximum age of the cookie in seconds. 2. public String getName():Returns the name of the cookie. The name cannot be changed after creation. 3. public String getValue():Returns the value of the cookie. For adding cookie or getting the value from the cookie, we need some methods provided by other interfaces.They are:

o public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in response object. o public Cookie[] getCookies():method of HttpServletRequest interface is used to return all the cookies from the browser.

Advantage of Cookies 1. Simplest technique of maintaining the state. 2. Cookies are maintained at client side. Disadvantage of Cookies 1. It will not work if cookie is disabled from the browser. 2. Only textual information can be set

2) Hidden Form Field


In case of Hidden Form Field an invisible text field is used for maintaining the state of an user. In such case, we store the information in the hidden field and get it from another servlet. This approach is better if we have to submit form in all the pages and we don't want to depend on the browser.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not. Disadvantage of Hidden Form Field: 1. It is maintained at server side. 2. Extra form submission is required on each pages. 3. Only textual information can be use

3)URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter name/value pairs using the following format: url?name1=value1&name2=value2&?? A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server. From a Servlet, we can use getParameter() method to obtain a parameter value.

Advantage of URL Rewriting 1. It will always work whether cookie is disabled or not (browser independent). 2. Extra form submission is not required on each pages. Disadvantage of URL Rewriting 1. It will work only with links. 2. It can send Only textual information

4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of HttpSession can be used to perform two tasks: 1. bind objects 2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed time. The HttpServletRequest interface provides two methods to get the object of HttpSession: 1. public HttpSession getSession():Returns the current session associated with this request, or if the request does not have a session, creates one. 2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.

Servlet Config :
An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration information from web.xml file. If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to manage the web application if any specific content is modified from time to time.

Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml file.

Methods of ServletConfig interface


1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns an enumeration of all the initialization parameter names. 3. public String getServletName():Returns the name of the servlet. 4. publicServletContextgetServletContext():Returns an object of ServletContext.

How to get the object of ServletConfig


1. getServletConfig() method of Servlet interface returns the object of ServletConfig. Syntax of getServletConfig() method
public ServletConfig getServletConfig();

Example of getServletConfig() method


ServletConfig config=getServletConfig(); //Now we can call the methods of ServletConfig interface

Syntax to provide the initialization parameter for a servlet The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
<web-app> <servlet> ...... <init-param>

<param-name>parametername</param-name> <param-value>parametervalue</param-value> </init-param> ...... </servlet> </web-app>

Servlet Context:
An object of ServletContext is created by the web container at time of deploying the project. This object can be used to get configuration information from web.xml file. There is only one ServletContext object per web application. If any information is shared to many servlet, it is better to provide it from the web.xml file using the <context-param>element.

Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it available for all the servlet. We provide this information from the web.xml file, so if the information is changed, we don't need to modify the servlet. Thus it removes maintenance problem.

Usage of ServletContext Interface


There can be a lot of usage of ServletContext object. Some of them are as follows: 1. The object of ServletContext provides an interface between the container and servlet. 2. The ServletContext object can be used to get configuration information from the web.xml file. 3. The ServletContext object can be used to set, get or remove attribute from the web.xml file. 4. The ServletContext object can be used to provide inter-application communication.

Commonly used methods of ServletContext interface

There is given some commonly used methods of ServletContext interface. 1. public String getInitParameter(String name):Returns the parameter value for the specified parameter name. 2. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters. 3. public void setAttribute(String name,Object object):sets the given object in the application scope. 4. public Object getAttribute(String name):Returns the attribute for the specified name. 5. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters as an Enumeration of String objects. 6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet context.

How to get the object of ServletContext interface


1. getServletContext() method of ServletConfig interface returns the object of ServletContext. 2. getServletContext() method of GenericServlet class returns the object of ServletContext. Syntax of getServletContext() method
publicServletContextgetServletContext()

Example of getServletContext() method


//We can get the ServletContext object from ServletConfig object ServletContext application=getServletConfig().getServletContext(); //Another convenient way to get the ServletContext object ServletContext application=getServletContext();

Syntax to provide the initialization parameter in Context scope


The context-param element, subelement of web-app, is used to define the initialization parameter in the application scope. The param-name and param-value are the sub-elements of the context-param. The param-name element defines parameter name and andparam-value defines its value.
<web-app> ......

<context-param> <param-name>parametername</param-name> <param-value>parametervalue</param-value> </context-param> ...... </web-app>

Вам также может понравиться