Servlet Notes

February 19, 2018 | Author: Ankit Jain | Category: Hypertext Transfer Protocol, Java Servlet, Web Server, Http Cookie, Java (Programming Language)
Share Embed Donate


Short Description

Download Servlet Notes...

Description

Web application:• A web application is nothing but a web site. • A web application can be thought of as a collection of two types of resources 1. Static Resources: - Normally non-executable resources. A web client can ask for any static resources by just specifying the URL. Web server simply returns the specified resources to the client without doing any processing. It May be:I. HTML II. Images/Audio and video files III. Applets IV. Documents / spreadsheet /text files etc.

2. Dynamic Resources :- they are Executable resources

• •

The dynamic resources are also accessed by directly or indirectly specifying the URL. But the action taken by web server is different in case of dynamic resources. In this case server executes the appropriate components and then returns the result to the client normally as HTML using HTTP protocol It may be:i. JSP ii. Servlets A web application is deploy on the web-server and are normally accessed through the web clients, which is normally a web browser. The communication between web client and web-server takes place through HTTP protocol.

CGI (Common Gateway Interface): CGI technology enables the web server to call an external program and pass HTTP request information to the external program to process the request.

Problems in CGI:

There are many problems in CGI technology: 1. If number of client increased, response time very less. 2. For each request, it starts a process. Web server is limited to start process. 3. It uses plateform dependent language e.g. C,C++,perl.

HTTP (Hyper Text Transfer Protocol): Http is the protocol that allows web servers and browsers to exchange data over the web. It is a stateless TCP/IP based protocol used for Communicating on the World Wide Web. HTTP defines the manner in which web clients communicate with web servers. Today, the most common version of this is HTTP/1.0.HTTP also called a connectionless protocol. A protocol is said to be stateless if it has no memory of prior connections and cannot distinguish one client’s request from that of another. The stateless nature of HTTP is both its strength and weakness. The strength is that its stateless nature keeps the protocol simple and straightforward. The disadvantage is in the overhead required to create a new connection with each request and the inability to track a single user. That is, using HTTP, a client opens a connection with the server, and sends requests, receives a response and closes the connection. Each request requires its own connection.

Now let us take a close look how HTTP helps to communicate between a web server and a web browser. There are generally four stages of a simple web transaction: 1. The client opens a connection to the server: First, the client opens a TCP/IP connection to the server. By default, the connection on the server is made to port 80, unless or otherwise specified. 2. The client makes a request to the server: Let us assume that the web browser makes a request to retrieve an HTML file. For this, the user enters the Required URL into the web browser. This request is broken into three parts: the request method, the source Name and the protocol. 3. The server responds to the request: The server gets the request from the browser. The server responds with a status code, various header files and If possible, contents of the request. 4.

Connection is closed Either the server or the client may close the connection. The server generally terminates the connection after The response has been sent. Similarly, a browser often closes the connection once the complete response has Been received.

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

HTTP Request Method

Description

GET

Asks to get the resource at the requested URL.

POST

Asks the server to accept the body info attached. It like a GET with extra info sent with the request.

HEAD

Asks for only the header part of whatever a GET would return. Just like GET but with no body.

TRACE

Asks for the loopback of the request message, for testing or troubleshooting.

PUT

Says to put the enclosed info (the body) at the requested URL.

DELETE

Says to delete the resource at the requested URL.

OPTIONS

Asks for a list of the HTTP methods to which the thing at the request URL can respond

Difference between Get and Post: There are many differences between the Get and Post request. Let's see these differences: GET POST 1) In case of Get request, only limited amount of data can In case of post request, large amount of data can be be sent because data is sent in header. sent because data is sent in body. 2) Get request is not secured because data is exposed in URL bar.

Post request is secured because data is not exposed in URL bar.

3) Get request can be bookmarked

Post request cannot be bookmarked

4) Get request is idempotent

Post request is non-idempotent

5) Get request is more efficient and used than Post

Post request is less efficient and used.

Anatomy of Get Request:

Anatomy of Post Request:

Content Type: Content Type is also known as MIME (Multipurpose internet Mail Extension) Type.It is a HTTP header that provides the description about what are you sending to the browser.There are many content types: • text/html • text/plain • application/msword • application/vnd.ms-excel • application/jar • application/pdf • application/octet-stream • application/x-zip • images/jpeg • vedio/quicktime etc.

What is a Servlet :1. A servlet is simply a java program that runs on the server. 2. Servlets are designed to accept a response from a client (usually a web browser), process that request,

3. 4.

5.

6. 7.

and return a response to the client. A good analogy for a servlet is a non-visual applet that runs on a server. A Servlet can be thought of as a server side applet. Servlets are loaded and executed by a web server in the same manner in which applets are loaded and executed by a web browser. Thus, we can say that Servlet is a server side software component, written in Java that dynamically extends the functionality of a server. With Servlet, Web developers can create fast and efficient server-side applications in Java instead of using CGI and Perl. A servlet’s work is done “behind the scene” on the server. The results of the Servlet are returned to the client usually in the form of HTML.

Advantage of Servlet:

There are many advantages of Servlet over CGI: 1. Better performance: because it creates a thread for each request not process. 2. Portability: because it uses java language. 3. Robust: Servlets are managed by JVM so no need to worry about memory leak, garbage collection etc. 4. Secure: because it uses java language.

Servlet Overview:A Java Servlet is a Java object that responds to HTTP requests. It runs inside a Servlet container. Here is an illustration of that:

Servlets inside a Java Servlet Container A Servlet is part of a Java web application. A Servlet container may run multiple web applications at the same time, each having multiple servlets running inside. Here is an illustration of that:

Web applications with multiple servlets inside a Java Servlet container A Java web application can contain other components than servlets. It can also contain Java Server Pages (JSP), Java Server Faces (JSF) and Web Services. This tutorial is about Java Servlets only, though.

HTTP Request and Response:The browser sends an HTTP request to the Java web server. The web server checks if the request is for a servlet. If it is, the servlet container is passed the request. The servlet container will then find out which servlet the request is for, and activate that servlet. The servlet is activated by calling the Servlet.service() method. Once the servlet has been activated via the service () method, the servlet processes the request, and generates a response. The response is then sent back to the browser.

Life Cycle of a Servlet (Servlet Life Cycle): A servlet follows a certain life cycle. The servlet life cycle is managed by the servlet container. The life cycle contains the following steps: 1. Load Servlet Class. 2. Create Instance of Servlet. 3. Call the servlets init () method. 4. Call the servlets service () method. 5. Call the servlets destroy () method.

The Java Servlet life cycle

1) Servlet class is loaded: The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created: The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle. 3) init method is invoked: The init method is called by the servlet container after the servlet class has been instantiated. The servlet container calls this method exactly once to indicate to the servlet that the servlet is being placed into service. The init method must complete successfully before the servlet can receive any requests. You can override this method to write initialization code that needs to run only once, such as loading a database driver, initializing values, and so on. In other cases, you normally leave this method blank. The signature of this method is as follows: public void init(ServletConfig config) throws ServletException The init method is important also because the servlet container passes a ServletConfig object, which contains the configuration values stated in the web.xml file for this application. 4) service method is invoked: The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below: public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException

5) destroy method is invoked:

The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below: public void destroy()

Steps to create the servlet using Tomcat server: There are five steps to create a servlet. These stepse are required for all the servers. We are using apache tomcat server in this example. The steps are as follows: 1. Create a directory structure 2. Create a Servlet 3. Compile the Servlet 4. Create a deployment descriptor 5. Start the server and deploy the application

1)Create a directory structures:

2)Create a Servlet:

//DemoServlet.java import import import public public throws

javax.servlet.http.*; javax.servlet.*; java.io.*; class DemoServlet extends HttpServlet{ void doGet(HttpServletRequest req,HttpServletResponse res) ServletException,IOException{ res.setContentType("text/html"); PrintWriter pw=res.getWriter(); pw.println(""); pw.println("Welcome to servlet"); pw.println("");

} }

3)Compile the servlet: For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar files: Jar file Server 1) servlet-api.jar

Apache Tomacat

2) weblogic.jar

Weblogic

3) javaee.jar

Glassfish

4) javaee.jar

JBoss

Two ways to load the jar file: 1. set classpath 2. paste the jar file in JRE/lib/ext folder Put the java file in any folder. After compiling the java file paste the class file of servlet in WEB-INF/classes folder.

4)Create the deployment descriptor: [ web.xml ] sonoojaiswal DemoServlet sonoojaiswal /welcome

Description of the elements of web.xml file: represents the whole application. is sub element of and represents the servlet.

is sub element of represents the name of the servlet. is sub element of represents the class of the servlet. is sub element of . It is used to map the servlet. is sub element of . This pattern is used at client side to invoke the servlet.

5)Start Server: To start Apache Tomcat server JAVA_HOME and JRE_HOME must be set in Environment variables. Go to My Computer properties  Click on advanced tab then environment variables  Click on the new tab of user variable  Write JAVA_HOME in variable name and paste the path of jdk folder in variable value  Ok  Ok  Ok

Servlet API: - Two packages are available:1.

javax.servlet :-

2.

javax.servlet.http :-

Servlet Interface:-

 Servlet interface is the central abstraction of the java servlet technology.  Every servlet you write must implements this interface either directly or indirectly (By subclassing the GenericServlet ot HttpServlet class).  It is collection of empty method signatures.

There are two main implementation of this interface. - GenericServlet :- used to create protocol independent servlet - HttpServlet :- used to create Http protocol specific servlet Servlet

| GenericServlet

HttpServlet

| (Protocol independent) MyServlet

| MyServlet (Http Specific)

Examples:package ServletBasic; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; public class ServletDemo implements Servlet { public void destroy() { } public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } public void init(ServletConfig arg0) throws ServletException { } public void service(ServletRequest req, ServletResponse res)throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("Hello, world!"); out.close(); } } ServletDemo ServletBasic.ServletDemo ServletDemo /ServletDemo

ServletConfig Interface: 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. 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. public ServletContext getServletContext():Returns an object of ServletContext.

Preserving The ServletConfig :You may want to have access to the ServletConfig object from the service() method, when you are servicing the user. In this case you need to preserve the ServletConfig object to a class level variable. This is not difficult. You need to create a ServletConfig object variable and set it to the ServletConfig object returned by the servlet container in init() method. package ServletBasic; import import import public

java.io.IOException; java.io.PrintWriter; javax.servlet.*; class PreserveServletConfigInfo implements Servlet { ServletConfig config; public void destroy() { } public ServletConfig getServletConfig() { return null;} public String getServletInfo() {return null; } public void init(ServletConfig arg0) throws ServletException { config = arg0; } public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { PrintWriter out = arg1.getWriter(); out.println(""); out.println(""); out.println("hiiiiiiiii"); out.println(""); out.println(""); out.println("Servlet Name :-" + config.getServletName()); out.println(""); out.println(""); }

} PreserveServletConfigInfo ServletBasic.PreserveServletConfigInfo PreserveServletConfigInfo /PreserveServletConfigInfo

Obtaining Configuration Information: ObtainConfInfo ServletBasic.ObtainConfInfo Email [email protected] Contact Number 9660242550 ObtainConfInfo /ObtainConfInfo package ServletBasic; import import import import

java.io.IOException; java.io.PrintWriter; java.util.Enumeration; javax.servlet.*;

public class ObtainConfInfo implements Servlet { ServletConfig config; public void destroy() { } public ServletConfig getServletConfig() { return null; } public String getServletInfo() { return null; } public void service(ServletRequest req,ServletResponse res) throws ServletException, IOException { Enumeration att = config.getInitParameterNames(); response.setContentType("html/text"); PrintWriter printWriter=response.getWriter(); while (att.hasMoreElements()) { String par = (String) att.nextElement(); printWriter.println("Param Name :-"+ par+""); printWriter.println("Param value:-"+ config.getInitParameter(par)+""); } } public void init(ServletConfig servletConfig) throws ServletException { config=servletConfig; Enumeration att = servletConfig.getInitParameterNames(); while (att.hasMoreElements()) { String par = (String) att.nextElement(); System.out.println("Param Name :-" + par); System.out.println("Param value :-"+ servletConfig.getInitParameter(par)); } } } Output:Param Name: - Email Param Value: - [email protected] Param Name: - contact Number`

Param Value: - 9660242550

ServletContext Interface : It is the environment where the servlet runs.

 All servlets belong to one servlet context. It can only be called at context initialization time.  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.  A servlet can also bind an object attribute into context by name ServletContext context= config.getServletContext(); context.setAttribute("password", "121212");

 Any object bound into context is available to any other servlet that is the part of the same application

Uses of ServletContext Interface: 1. 2. 3. 4. 5.

The object of ServletContext provides an interface between the container and servlet. The ServletContext object can be used to get configuration information from the web.xml file. The ServletContext object can be used to set, get or remove attribute from the web.xml file. The ServletContext object can be used to provide inter-application communication. Finding path information

6. Writing the server log file.

Commonly used methods of ServletContext interface: 1. 2. 3. 4. 5.

public String getInitParameter(String name):Returns the parameter value for the specified parameter name. public Enumeration getInitParameterNames():Returns the names of the context's initialization parameters. public void setAttribute(String name,Object object):sets the given object in the application scope. public Object getAttribute(String name):Returns the attribute for the specified name. 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: 1. getServletContext() method of ServletConfig interface returns the object of ServletContext.

For Example: ServletContext context=getServletConfig().getServletContext(); 2. getServletContext() method of GenericServlet class returns the object of ServletContext. For Example: ServletContext context=getServletContext();

Syntax to provide the initialization parameter in Context scope: parametername

parametervalue

Retrieving Servlet Context Information:package ServletBasic; import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class ContextDemoServlet implements Servlet { ServletConfig servletConfig; public void init(ServletConfig config) throws ServletException { servletConfig = config; } public void destroy() { } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ServletContext servletContext = servletConfig.getServletContext(); Enumeration attributes = servletContext.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); System.out.println("Attribute name : " + attribute); System.out.println("Attribute value : " + servletContext.getAttribute(attribute)); } System.out.println("Major version : " + servletContext.getMajorVersion()); System.out.println("Minor version : " + servletContext.getMinorVersion()); System.out.println("Server info : " + servletContext.getServerInfo()); } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; } } ContextDemoServlet ServletBasic.ContextDemoServlet ContextDemoServlet /ContextDemoServlet

Sharing Information Among Servlets :AttributeSetterServlet package ServletBasic; import javax.servlet.*; import java.io.IOException; public class AttributeSetterServlet implements Servlet { public void init(ServletConfig config) throws ServletException { ServletContext servletContext = config.getServletContext(); servletContext.setAttribute("password", "dingdong"); } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { } public void destroy() { } public String getServletInfo() { return null; }

}

public ServletConfig getServletConfig() { return null; }

AttributeSetterServlet ServletBasic.AttributeSetterServlet AttributeSetterServlet /AttributeSetterServlet

DisplayAttributesServlet package ServletBasic; import javax.servlet.*; import java.io.IOException; import java.util.Enumeration; public class ResponseDemoServlet implements Servlet { ServletConfig servletConfig; public void init(ServletConfig config) throws ServletException { servletConfig = config; } public void destroy() {

} public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { ServletContext servletContext = servletConfig.getServletContext(); Enumeration attributes = servletContext.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); System.out.println("Attribute name : " + attribute); System.out.println("Attribute value : "+ servletContext.getAttribute(attribute)); } } public String getServletInfo() { return null; }

}

public ServletConfig getServletConfig() { return null; }

ResponseDemoServlet ServletBasic.ResponseDemoServlet ResponseDemoServlet /ResponseDemoServlet

Output :Attribute Attribute Attribute Attribute Attribute Attribute

name value name value name value

: : : : : :

javax.servlet.context.tempdir C:\123data\JavaProjects\JavaWebBook\work\localhost_8080 password dingdong sun.servlet.workdir C:\123data\JavaProjects\JavaWebBook\work\localhost_8080

ServletRequest Interface: Whenever the web container receives a request from the web browser, it creates a servlet request and

identifies which servlet needs to be invoked based on the URL mapping, calls the service method of the servlet and passes the servlet request object as parameter.  ServletRequest interface encapsulates the communication from the client to the server.

Methods of ServletRequest Interface: 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():retuns an enumeration of all of the request parameter names. 4. public int 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. public int getServerPort():Returns the port number on which this request was received.

ServletResponse Interface:  This interface represents the response from the servlet to a web client. Methods of ServletRequest Interface: void flushBuffer()

Forces any content in the buffer to be written to the client.

int getBufferSize()

Returns the actual buffer size used for the response.

String getCharacterEncoding()

Returns the name of the character encoding (MIME charset) used for the body sent in this response.

String getContentType()

Returns the content type used for the MIME body sent in this response.

java.util.Locale getLocale()

Returns the locale specified for this response using the setLocale(java.util.Locale) method.

ServletOutputStream

Returns a ServletOutputStream suitable for writing binary data in the response.

getOutputStream()

java.io.PrintWriter getWriter()

Returns a PrintWriter object that can send character text to the client.

Boolean isCommitted()

Returns a boolean indicating if the response has been committed.

void reset()

Clears any data that exists in the buffer as well as the status code and headers.

void resetBuffer()

Clears the content of the underlying buffer in the response without clearing headers or status code.

void setBufferSize(int size)

Sets the preferred buffer size for the body of the response.

void

Sets the character encoding (MIME charset) of the response being sent to

setCharacterEncoding(String charset) the client, for example, to UTF-8. void setContentLength(int len)

Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.

void setContentType(String type)

Sets the content type of the response being sent to the client, if the response has not been committed yet.

void setLocale(java.util.Locale loc) Sets the locale of the response, if the response has not been committed yet.

SingleThreadModel:Servlet in java application can be accessed by multiple users at a same time. SingleThreadModel is deprecated. Although it is not good thing to use SingleThreadModel in servlet, we can use it to restrict access of more than one user at a same time. SingleThreadModel is useful in case you required to process one request at one time, no other can access that process when servlet is in use. To make servlet interface.

a

Single

thread,

need

to

implement

SingleThreadModel

The example is given of SingleThreadModel in Servlet. import javax.servlet.SingleThreadModel; import javax.servlet.http.HttpServlet; public class TestServlet extends HttpServlet implements SingleThreadModel { }

GenericServlet : It is an abstract class and implements Servlet interface, ServletConfig interface and Serializable interface.  Writing servlet by extending GenericServlet is easy comparison to creating a servlet by implementing the Servlet interface. Because in the case of Servlet Interface we have to provide all the methods implementation. Even if we use or not.  In GenericServlet service method is abstract . so when we extend this class to create a servlet then we must provide the implementation of this method.  We write our code in this method. Example :import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; public class SimpleServlet extends GenericServlet { public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException { PrintWriter out = res.getWriter(); out.println(""); out.println(""); out.println(""); out.println("Extending GenericServlet"); out.println(""); out.println(""); out.println(""); out.println("Extending GenericServlet makes your code simpler."); out.println(""); out.println(""); } }

javax.servlet.http : This package is used to develop servlet that supports the HTTP protocol.

 This package is much rich and more convenient to use rather than javax.servlet package.  The classes and interfaces of this package are derived from the javax.servlet package.  This package supports the cookie, session concepts. HttpServlet Class : This class extends the GenericServlet.  It is specific to the http protocol.  It is the most used class in the servlet.  It is present in the javax.servlet.http package.  It contains the methods such as doGet(),doPost(),doDelete(),doHeader() etc. Methods are:• doGet() • doPost() • doDelete() • doHeader() • doPut() • service() It has two overridden version of service() method • protected void service(HttpServletRequest req, HttpServletResponse resp) • public void service(ServletRequest req, ServletResponse res) • •

First client request comes to the public void service() method It then dispatches client requests to the protected service method.



protected service() method receives HTTP requests from the public service method and dispatches them to the do...() methods defined in this class.

So the calling functions flow is like this Client  public service()  protected service  doXXX() doGet() o o o o o

This method is used for handling the get request. It is called by the service methods. This supports the HTTP HEAD request. HEAD request is a GET request. It returns no body. It returns the request header fields.

o o

In these methods values passing from form to the server get added to the URL. It allows limited data to be passed

doPost () o o o o o

This method is used for handling the post request. It is called by the service methods. In this method values passing from to the server get added to the body instead of the URL. Using the HTTP post method the user can send data of unlimited length to the Web server. It is used mostly as the information sending is more secure such as credit card, debit card information.

Sends an HTTP request to the server using the POST method:When the user clicks the Submit button to submit the form, the browser sends an HTTP request to the server using the POST method. The web server then passes this request to the servlet and the doPost method of the servlet is invoked. Using the POST method in a form, the parameter name/value pairs of the form are sent in the request body. For example, if you use the below form as an example and enter Ankit as the value for firstName and Jain as the value for lastName, you will get the following result in the request body: Ankit First HTTP Servlet DEMO

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;

Program of sendRedirect() method DemoServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class DemoServlet extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException { res.setContentType("text/html"); PrintWriter pw=res.getWriter(); response.sendRedirect("http://www.google.com"); pw.close(); }}

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.

Methods of RequestDispatcher: 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.

Program of RequestDispatcher:

index.html Name: Password:

import import import import

java.io.IOException; java.io.PrintWriter; javax.servlet.*; javax.servlet.http.*;

public class Login extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String n=req.getParameter("userName"); String p=req.getParameter("userPass"); if(p.equals("servlet")){ RequestDispatcher rd=req.getRequestDispatcher("servlet2"); rd.forward(req, res); } else{ out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=req.getRequestDispatcher("/index.html"); rd.include(req, res); } } }

WelcomeServlet.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n = request.getParameter("userName"); out.print("Welcome " + n); } }

web.xml Login Login WelcomeServlet WelcomeServlet Login /servlet1 WelcomeServlet /servlet2 index.html

Attribute in Servlet: An attribute is an object that can be set,get or removed from one of the following scopes: 1. request scope

2. session scope 3. application scope

Attribute specific methods of ServletRequest,HttpSession and ServletContext interface: 1. public void setAttribute(String name,Object object):sets the given object in the application scope. 2. public Object getAttribute(String name):Returns the attribute for the specified name. 3. public Enumeration getInitParameterNames():Returns the names of the context's initialization

parameters as an Enumeration of String objects. 4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet

context.

Program of ServletContext to set and get attribute: DemoServlet1.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class DemoServlet1 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); context.setAttribute("company","IBM"); out.println("Welcome to first servlet"); out.println("visit"); out.close(); }catch(Exception e){out.println(e);} }}

DemoServlet2.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class DemoServlet2 extends HttpServlet{ public void doGet(HttpServletRequest req,HttpServletResponse res) { try{ res.setContentType("text/html"); PrintWriter out=res.getWriter(); ServletContext context=getServletContext(); String n=(String)context.getAttribute("company"); out.println("Welcome to "+n); out.close(); }catch(Exception e){out.println(e);} }}

web.xml s1 DemoServlet1 s1 /servlet1 s2 DemoServlet2 s2 /servlet2

Difference between ServletConfig and ServletContext: The servletconfig object refers to the single servlet whereas servletcontext object refers to the whole web application.

Cookies in 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.

Why use Session Tracking? To recognize the 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.A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number.

javax.servlet.http.Cookie class: javax.servlet.http.Cookie class provides the functionality of using cookies.

Constructor: Cookie(String name, String value): Constructs a cookie with a specified name and value.

Commonly used methods: 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.

Other methods required for using Cookies: 1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add cookie in

response object. 2. 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 in Cookie object.

Example of using Cookies:

index.html Name:

FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class FirstServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); Cookie ck=new Cookie("uname",n); response.addCookie(ck); out.print(""); out.print(""); out.print(""); out.close();

}catch(Exception e){System.out.println(e);} } }

SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); Cookie ck[]=request.getCookies(); out.print("Hello "+ck[0].getName()); out.close(); }catch(Exception e){System.out.println(e);} }

}

web.xml s1 FirstServlet s1 /servlet1 s2 SecondServlet s2 /servlet2



2)Hidden Form Field: In case of Hidden Form Field an invisible textfield is used for maintaing the state of an user.

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 used.

Example of using Hidden Form Field: index.html

Name:

FirstServlet.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print(""); out.print(""); out.print(""); out.print(""); out.close(); }catch(Exception e){System.out.println(e);} } }

SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);}

}

}

web.xml s1 FirstServlet s1 /servlet1 s2 SecondServlet s2 /servlet2

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.

Example of using URL Rewriting: index.html Name:

FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{

response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); out.print("visit"); out.close(); }catch(Exception e){System.out.println(e);} } }

SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} }

}

web.xml s1 FirstServlet s1 /servlet1

s2 SecondServlet s2 /servlet2

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.

How to get HttpSession object? 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.

Commonly used methods of HttpSession interface: 1. public String getId():Returns a string containing the unique identifier value. 2. public long getCreationTime():Returns the time when this session was created, measured in milliseconds

since midnight January 1, 1970 GMT. 3. public long getLastAccessedTime():Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT. 4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession: index.html Name:

FirstServlet.java import java.io.*;

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

public class FirstServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); HttpSession session=request.getSession(); session.setAttribute("uname",n); out.print("visit"); out.close(); }catch(Exception e){System.out.println(e);} } }

SecondServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SecondServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session=request.getSession(false); String n=(String)session.getAttribute("uname"); out.print("Hello "+n); out.close(); }catch(Exception e){System.out.println(e);} }

}

web.xml

s1 FirstServlet s1 /servlet1 s2 SecondServlet s2 /servlet2

Filter: A filter is an object that is used to performed filtering tasks such as conversion,log maintain,compression,encryption and decryption,input validation etc.A filter is invoked at the preprocessing and postprocessing of a request.

Uses of Filter:



recording all incoming requests logs the IP addresses of the computers from which the requests originate conversion data compression encryption and decryption



input validation etc.

• • • •

Advantage of Filter: 1. Filter is pluggable. 2. One filter don't have dependency onto another resource.

Filter API Like servlet filter have its own API.The javax.servlet package contains the three interfaces of Filter API 1. Filter 2. FilterChain 3. FilterConfig

1) Filter interface For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter. 1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter. 2. public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain):

doFilter() method is invoked every time when user request to any resource, to which the filter is mapped.It is used to perform filtering tasks. 3. public void destroy():This is invoked only once when filter is taken out of the service.

2) FilterChain interface The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter method of Filter interface.The FilterChain interface contains only one method: 1. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control

to the next filter or resource.

3) FilterConfig interface For creating any filter, you must implement the Filter interface.Filter interface provides the life cycle methods for a filter.

1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter. 2. public String getInitParameter(String parameterName): Returns the parameter value for the specified

parameter name. 3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter names. 4. public ServletContext getServletContext(): Returns the ServletContext object.

Simple Example of Filter: index.html Name:

MyFilter.java import java.io.*; import javax.servlet.*; public class MyFilter implements Filter{ public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { PrintWriter out=res.getWriter(); chain.doFilter(req, res); out.print("filter invoked.."); } public void destroy() {} }

FirstServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){ try{ response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("Welcome servlet"); out.close(); }catch(Exception e){System.out.println(e);} } }

web.xml s1 FirstServlet s1 /servlet1 f1 MyFilter f1 /servlet1 index.html

Useful Filter Programs

Program of sending response by filter only MyFilter.java import java.io.*; import javax.servlet.*; public class MyFilter implements Filter{ public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { PrintWriter out=res.getWriter(); out.print("this site is underconstruction.."); out.close(); } public void destroy() {} }

Program of counting number of visitors for a single page MyFilter.java import java.io.*; import javax.servlet.*; public class MyFilter implements Filter{ static int count=0; public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { PrintWriter out=res.getWriter(); chain.doFilter(request,response); out.print("Total visitors "+(++count)); out.close(); } public void destroy() {} }

Program of checking total response time MyFilter.java

import java.io.*; import javax.servlet.*; public class MyFilter implements Filter{ static int count=0; public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { PrintWriter out=res.getWriter(); long before=System.currentTimeMillis(); chain.doFilter(request,response); long after=System.currentTimeMillis(); out.print("Total response time "+(after-before)+" miliseconds"); out.close(); } public void destroy() {} }

Servlet with Annotation (feature of servlet3): Annotation represents the metadata. If you use annotation, deployment descriptor (web.xml file) is not required. But you should have tomcat7 as it will not run in the previous versions of tomcat. @WebServlet annotation is used to map the servlet with the specified name.

Example of simple servlet by annotation Simple.java import java.io.IOException; import java.io.PrintWriter; import import import import import

javax.servlet.ServletException; javax.servlet.annotation.WebServlet; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse;

@WebServlet("/Simple") public class Simple extends HttpServlet { private static final long serialVersionUID = 1L;

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html"); PrintWriter out=response.getWriter(); out.print(""); out.print("Hello Servlet"); out.print(""); } }

download this example

View more...

Comments

Copyright ©2017 KUPDF Inc.
SUPPORT KUPDF