0% found this document useful (0 votes)
13 views

Unit 4servlets

Uploaded by

Chitti Chitti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Unit 4servlets

Uploaded by

Chitti Chitti
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

UNIT-IV

Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).

o Servlet technology is robust and scalable because of java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was common as a server-side
proServlet is a technology which is used to create a web application.
o Servlet is an API that provides many interfaces and classes including
documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic
web page.

What is a 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 elements such as
HTML, CSS, and JavaScript. The web components typically execute in Web Server and
respond to the HTTP request.

CGI (Common Gateway Interface)

Veda.kotagiriPage 1
UNIT-IV
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
There are many problems in CGI technology:
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.

Advantages of Servlet

Veda.kotagiriPage 2
UNIT-IV

There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the Servlet. Threads have many benefits over the
Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage
collection, etc.
4. Secure: because it uses java language.

Life Cycle of a Servlet (Servlet Life Cycle)


1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of
the servlet:
1. Servlet class is loaded.
2. Servlet instance is created.
3. init method is invoked.

Veda.kotagiriPage 3
UNIT-IV
4. service method is invoked.
5. destroy method is invoked.

As displayed in the above diagram, there are three states of a servlet: new, ready and end.
The servlet is in new state if servlet instance is created. After invoking the init() method,
Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When
the web container invokes the destroy() method, it shifts to the end state.

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.

Veda.kotagiriPage 4
UNIT-IV

3) init method is invoked


The web container calls the init method only once after creating the servlet instance. The init method is
the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is gi
1. public void init(ServletConfig config) throws ServletException

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:

1. public void service(ServletRequest request, ServletResponse response)


2. 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:

1. public void destroy()

created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request
specific method such as doGet(), doPost(), doHead() e

1. mport javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data

Veda.kotagiriPage 5
UNIT-IV
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}

Servlet API
1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and classes that are used by the servlet or web
container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http requests
only.

Let's see what are the interfaces of javax.servlet package.

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext

Veda.kotagiriPage 6
UNIT-IV
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package


There are many classes in javax.servlet.http package. They are as follows:

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent

Veda.kotagiriPage 7
UNIT-IV
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface

Servlet interface provides common behaviour to all the servlets.

Servlet interface needs to be implemented for creating any servlet (either directly or indirectly). It
provides 3 life cycle methods that are used to initialize the servlet, to service the requests, and to
destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface


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.

Method Description
Public void init(ServletConfig initializes the servlet. It is the life cycle method of servlet and invoked by
config) the web container only once.

public void provides response for the incoming request. It is invoked at each request by
service(ServletRequest the web container.
request,ServletResponse
response)

public void destroy() is invoked only once and indicates that servlet is being destroyed.

public ServletConfig returns the object of ServletConfig.


getServletConfig()

public String returns information about servlet such as writer, copyright, version etc.
getServletInfo()

GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides


the implementation of all the methods of these interfaces except the service method.

Veda.kotagiriPage 8
UNIT-IV
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.

Methods of GenericServlet class


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.
6. public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.
12. public void log(String msg,Throwable t) writes the explanatory message in the servlet log
file and a stack trace.
13. import java.io.*;
14. import javax.servlet.*;
15. public class First extends GenericServlet{
16. public void service(ServletRequest req,ServletResponse res) throws IOException,ServletExc
eption{
17. res.setContentType("text/html");
18. PrintWriter out=res.getWriter();
19. out.print("<html><body>");
20. out.print("<b>hello generic servlet</b>");
21. out.print("</body></html>");
22. }
23. }

HttpServlet class
1. HttpServlet class
2. Methods of 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.

Methods of HttpServlet class


Veda.kotagiriPage 9
UNIT-IV
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.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the
PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles
the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles
the DELETE request. It is invoked by the web container.
10. protected long getLastModified(HttpServletRequest req) returns the time when
HttpServletRequest was last modified since midnight January 1, 1970 GMT.

ServletRequest Interface
1. ServletRequest Interface
2. Methods of ServletRequest interface
3. Example of ServletRequest interface
4. Displaying all the header information

An object of ServletRequest is used to provide the client request information to a servlet such as
content type, content length, parameter names and values, header informations, attributes etc.

Methods of ServletRequest interface

There are many methods defined in the ServletRequest interface. Some of them are as follows:

Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.

public String[] getParameterValues(String returns an array of String containing all values of given parameter
name) name. It is mainly used to obtain values of a Multi select list box.

java.util.Enumeration getParameterNames() returns an enumeration of all of the request parameter names.

public int getContentLength() Returns the size of the request entity data, or -1 if not known.

Veda.kotagiriPage 10
UNIT-IV

public String getCharacterEncoding() Returns the character set encoding for the input of this request.

public String getContentType() Returns the Internet Media Type of the request entity data, or null if
not known.

public ServletInputStream getInputStream() Returns an input stream for reading binary data in the request body.
throws IOException

public abstract String getServerName() Returns the host name of the server that received the request.

public int getServerPort() Returns the port number on which this request was received.

Example of ServletRequest to display the name of the user


In this example, we are displaying the name of the user in the servlet. For this purpose, we have used
the getParameter method that returns the value for the given request parameter name.

index.html
1. <form action="welcome" method="get">
2. Enter your name<input type="text" name="name"><br>
3. <input type="submit" value="login">
4. </form>

DemoServ.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServ extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");
9. PrintWriter pw=res.getWriter();
10. String name=req.getParameter("name");//will return value
11. pw.println("Welcome "+name);
12. pw.close();
13. }}

RequestDispatcher in Servlet
1. RequestDispatcher Interface
2. Methods of RequestDispatcher interface
1. forward method
2. include method
3. How to get the object of RequestDispatcher
4. Example of RequestDispatcher interface

The RequestDispatcher 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.

There are two methods defined in the RequestDispatcher interface.

Veda.kotagiriPage 11
UNIT-IV

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

As you see in the above figure, response of second servlet is sent to the client. Response of the first
servlet is not displayed to the user.

As you can see in the above figure, response of second servlet is included in the response of the
first servlet that is being sent to the client.

How to get the object of RequestDispatcher

Veda.kotagiriPage 12
UNIT-IV
The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method


1. public RequestDispatcher getRequestDispatcher(String resource);

Example of using getRequestDispatcher method


1. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
2. //servlet2 is the url-pattern of the second servlet
3.
4. rd.forward(request, response);//method may be include or forward

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is servlet, it will
forward the request to the WelcomeServlet, otherwise will show an error message: sorry username or
password error!. In this program, we are cheking for hardcoded information. But you can check it to
the database also that we will see in the development chapter. In this example, we have created
following files:

o index.html file: for getting input from the user.


o Login.java file: a servlet class for processing the response. If password is servet, it will
forward the request to the welcome servlet.
o WelcomeServlet.java file: a servlet class for displaying the welcome message.
o web.xml file: a deployment descriptor file that contains the information about the servlet.

Veda.kotagiriPage 13
UNIT-IV
index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. Password:<input type="password" name="userPass"/><br/>
4. <input type="submit" value="login"/>
5. </form>

Login.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class Login extends HttpServlet {
6. public void doPost(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. String n=request.getParameter("userName");
11. String p=request.getParameter("userPass");
12. if(p.equals("servlet"){
13. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
14. rd.forward(request, response);
15. }
16. else{
17. out.print("Sorry UserName or Password Error!");
18. RequestDispatcher rd=request.getRequestDispatcher("/index.html");
19. rd.include(request, response);
20. } } }

WelcomeServlet.java

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

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>

Veda.kotagiriPage 14
UNIT-IV
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10. <servlet-mapping>
11. <servlet-name>Login</servlet-name>
12. <url-pattern>/servlet1</url-pattern>
13. </servlet-mapping>
14. <servlet-mapping>
15. <servlet-name>WelcomeServlet</servlet-name>
16. <url-pattern>/servlet2</url-pattern>
17. </servlet-mapping>
18. <welcome-file-list>
19. <welcome-file>index.html</welcome-file>
20. </welcome-file-list>
21. </web-app>

SendRedirect in servlet
1. sendRedirect method
2. Syntax of sendRedirect() method
3. Example of RequestDispatcher interface

The sendRedirect() method of HttpServletResponse interface can be used to redirect response to


another resource, it may be servlet, jsp or html file.

It accepts relative as well as absolute URL.

It works at client side because it uses the url bar of the browser to make another request. So, it can
work inside and outside the server.

Difference between forward() and sendRedirect() method


There are many differences between the forward() method of RequestDispatcher and sendRedirect()
method of HttpServletResponse interface. They are given below:

forward() method sendRedirect() method

The forward() method works at server side. The sendRedirect() method works at client side.

It sends the same request and response objects to It always sends a new request.
another servlet.

It can work within the server only. It can be used within and outside the server.

Example: Example: response.sendRedirect("servlet2");


request.getRequestDispacher("servlet2").forward(re
quest,response);

Veda.kotagiriPage 15
UNIT-IV

Syntax of sendRedirect() method

1. public void sendRedirect(String URL)throws IOException;

Example of sendRedirect() method

1. response.sendRedirect("http://www.adfff.com");

Full example of sendRedirect method in servlet


In this example, we are redirecting the request to the google server. Notice that sendRedirect
method works at client side, that is why we can our request to anywhere. We can send our
request within and outside the server.

DemoServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");
9. PrintWriter pw=res.getWriter();
10. response.sendRedirect("http://www.google.com");
11. pw.close();
12. }}

Creating custom google search using sendRedirect


In this example, we are using sendRedirect method to send request to google server with the request
data.

index.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>sendRedirect example</title>
6. </head>
7. <body>
8. <form action="MySearcher">
9. <input type="text" name="name">
10. <input type="submit" value="Google Search">
11. </form>
12.
13. </body>
14. </html>
MySearcher.java

1. import java.io.IOException;

Veda.kotagiriPage 16
UNIT-IV
2. import javax.servlet.ServletException;
3. import javax.servlet.http.HttpServlet;
4. import javax.servlet.http.HttpServletRequest;
5. import javax.servlet.http.HttpServletResponse;
6.
7. public class MySearcher extends HttpServlet {
8. protected void doGet(HttpServletRequest request, HttpServletResponse response)
9. throws ServletException, IOException {
10. String name=request.getParameter("name");
11. response.sendRedirect("https://www.google.co.in/#q="+name);
12. }
13. }

ServletConfig Interface
1. ServletConfig Interface
2. Methods of ServletConfig interface
3. How to get the object of ServletConfig
4. Syntax to provide the initialization parameter for a servlet
5. Example of ServletConfig to get initialization parameter
6. Example of ServletConfig to get all the initialization parameter

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

How to get the object of ServletConfig


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

Veda.kotagiriPage 17
UNIT-IV

Syntax of getServletConfig() method


1. public ServletConfig getServletConfig();

Example of getServletConfig() method

1. ServletConfig config=getServletConfig();
2. //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.

1. <web-app>
2. <servlet>
3. ......
4. <init-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </init-param>
8. ......
9. </servlet>
10. </web-app>

Example of ServletConfig to get initialization parameter


In this example, we are getting the one initialization parameter from the web.xml file and printing this
information in the servlet.

DemoServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. throws ServletException, IOException {
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. ServletConfig config=getServletConfig();
10. String driver=config.getInitParameter("driver");
11. out.print("Driver is: "+driver);
12. out.close();
13. } }

web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>DemoServlet</servlet-name>
4. <servlet-class>DemoServlet</servlet-class>
5. <init-param>
6. <param-name>driver</param-name>
7. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
8. </init-param>
9. </servlet>

Veda.kotagiriPage 18
UNIT-IV
10. <servlet-mapping>
11. <servlet-name>DemoServlet</servlet-name>
12. <url-pattern>/servlet1</url-pattern>
13. </servlet-mapping>
11. </web-app>

Example of ServletConfig to get all the initialization parameters


In this example, we are getting all the initialization parameter from the web.xml file and printing this
information in the servlet.

DemoServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import java.util.Enumeration;
4. import javax.servlet.*;
5. import javax.servlet.http.*;
6. public class DemoServlet extends HttpServlet {
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11. ServletConfig config=getServletConfig();
12. Enumeration<String> e=config.getInitParameterNames();
13. String str="";
14. while(e.hasMoreElements()){
15. str=e.nextElement();
16. out.print("<br>Name: "+str);
17. out.print(" value: "+config.getInitParameter(str));
18. }
19. out.close();
20. } }

web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>username</param-name>
9. <param-value>system</param-value>
10. </init-param>
11.
12. <init-param>
13. <param-name>password</param-name>
14. <param-value>oracle</param-value>
15. </init-param>
16.
17. </servlet>
18.
19. <servlet-mapping>
20. <servlet-name>DemoServlet</servlet-name>
21. <url-pattern>/servlet1</url-pattern>

Veda.kotagiriPage 19
UNIT-IV
22. </servlet-mapping>
23.
24. </web-app>

ServletContext Interface
1. ServletContext Interface
2. Usage of ServletContext Interface
3. Methods of ServletContext interface
4. How to get the object of ServletContext
5. Syntax to provide the initialization parameter in Context scope
6. Example of ServletContext to get initialization parameter
7. Example of ServletContext to get all the initialization parameter

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.

Veda.kotagiriPage 20
UNIT-IV

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


1. public ServletContext getServletContext()

Example of getServletContext() method


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

Veda.kotagiriPage 21
UNIT-IV

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 and param-value
defines its value.

1. <web-app>
2. ......
3.
4. <context-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </context-param>
8. ......
9. </web-app>

Example of ServletContext to get the initialization parameter


In this example, we are getting the initialization parameter from the web.xml file and printing the
value of the initialization parameter. Notice that the object of ServletContext represents the
application scope. So if we change the value of the parameter from the web.xml file, all the
servlet classes will get the changed value. So we don't need to modify the servlet. So it is better
to have the common information for most of the servlets in the web.xml file by context-param
element. Let's see the simple example:

DemoServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. res.setContentType("text/html");
11. PrintWriter pw=res.getWriter();
12.
13. //creating ServletContext object
14. ServletContext context=getServletContext();
15.
16. //Getting the value of the initialization parameter and printing it
17. String driverName=context.getInitParameter("dname");
18. pw.println("driver name is="+driverName);
19.
20. pw.close();
21.
22. }}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>

Veda.kotagiriPage 22
UNIT-IV
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <servlet-mapping>
14. <servlet-name>sonoojaiswal</servlet-name>
15. <url-pattern>/context</url-pattern>
16. </servlet-mapping>
17.
18. </web-app>

Example of ServletContext to get all the initialization parameters


In this example, we are getting all the initialization parameter from the web.xml file. For getting
all the parameters, we have used the getInitParameterNames() method in the servlet class.

DemoServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class DemoServlet extends HttpServlet{
6. public void doGet(HttpServletRequest req,HttpServletResponse res)
7. throws ServletException,IOException
8. {
9. res.setContentType("text/html");
10. PrintWriter out=res.getWriter();
11.
12. ServletContext context=getServletContext();
13. Enumeration<String> e=context.getInitParameterNames();
14.
15. String str="";
16. while(e.hasMoreElements()){
17. str=e.nextElement();
18. out.print("<br> "+context.getInitParameter(str));
19. }
20. }}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <context-param>
14. <param-name>username</param-name>
15. <param-value>system</param-value>

Veda.kotagiriPage 23
UNIT-IV
16. </context-param>
17.
18. <context-param>
19. <param-name>password</param-name>
20. <param-value>oracle</param-value>
21. </context-param>
22.
23. <servlet-mapping>
24. <servlet-name>sonoojaiswal</servlet-name>
25. <url-pattern>/context</url-pattern>
26. </servlet-mapping>
27.
28. </web-app>

Difference between ServletConfig and ServletContext


The servletconfig object refers to the single servlet whereas servletcontext object refers to the
whole web application.

Session Tracking in Servlets


1. Session Tracking
2. Session Tracking Techniques

Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques. 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.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure
given below:

Veda.kotagiriPage 24
UNIT-IV

Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

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

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent
by the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie
Veda.kotagiriPage 25
UNIT-IV
It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

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.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful
methods for cookies.

Constructor of Cookie class

Constructor Description
Cookie() constructs a cookie.

Cookie(String name, String value) constructs a cookie with a specified name and value.

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.

public String getName() Returns the name of the cookie. The name cannot be changed after creatio

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other methods required for using Cookies


For adding cookie or getting the value from the cookie, we need some methods provided by other

Veda.kotagiriPage 26
UNIT-IV
interfaces. They are:
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.

How to create Cookie?


Let's see the simple code to create cookie.

1. Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


2. response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

1. Cookie ck=new Cookie("user","");//deleting value of cookie


2. ck.setMaxAge(0);//changing the maximum age to 0 seconds
3. response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in another
servlet. As we know well that session corresponds to the particular user. So if you access it from too
many browsers with different values, you will get the different value.

Veda.kotagiriPage 27
UNIT-IV

index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet1extends HttpServlet {
6. public void doPost(HttpServletRequest request, HttpServletResponse response){
7. try{
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10.
11. String n=request.getParameter("userName");
12. out.print("Welcome "+n);
13. Cookie ck=new Cookie("uname",n);//creating cookie object
14. response.addCookie(ck);//adding cookie in the response
15. //creating submit button
16. out.print("<form action='servlet2'>");
17. out.print("<input type='submit' value='go'>");
18. out.print("</form>");
19. out.close();
20. }catch(Exception e){System.out.println(e);}
21. } }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {

Veda.kotagiriPage 28
UNIT-IV
5. public void doPost(HttpServletRequest request, HttpServletResponse response){
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. Cookie ck[]=request.getCookies();
10. out.print("Hello "+ck[0].getValue());
11. out.close();
12. }catch(Exception e){System.out.println(e);}
13. } }

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>FirstServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>s2</servlet-name>
12. <servlet-class>SecondServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>s2</servlet-name>
16. <url-pattern>/servlet2</url-pattern>
17. </servlet-mapping>
18. </web-app>

2) Hidden Form Field


In case of Hidden Form Field a hidden (invisible) textfield 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.

Let's see the code to store value in hidden field.

1. <input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page name in the
hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field

Veda.kotagiriPage 29
UNIT-IV
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.

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.

Veda.kotagiriPage 30
UNIT-IV
2. It can send Only textual information.

Example of using URL Rewriting


In this example, we are maintaning the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query string in
another page.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class FirstServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response){
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. String n=request.getParameter("userName");
10. out.print("Welcome "+n);
11. //appending the username in the query string
12. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
13. out.close();
14. }catch(Exception e){System.out.println(e);}
15. } }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. //getting value from the query string
10. String n=request.getParameter("uname");
11. out.print("Hello "+n);
12. out.close();
13. }catch(Exception e){System.out.println(e);}
14. } }

web.xml

1. <web-app>

Veda.kotagiriPage 31
UNIT-IV
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>FirstServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>s2</servlet-name>
12. <servlet-class>SecondServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>s2</servlet-name>
16. <url-pattern>/servlet2</url-pattern>
17. </servlet-mapping>
18. </web-app>

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

Veda.kotagiriPage 32
UNIT-IV
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


In this example, we are setting the attribute in the session scope in one servlet and getting that value
from the session scope in another servlet. To set the attribute in the session scope, we have used the
setAttribute() method of HttpSession interface and to get the attribute, we have used the getAttribute
method.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class FirstServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response){
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. String n=request.getParameter("userName");
10. out.print("Welcome "+n);
11. HttpSession session=request.getSession();
12. session.setAttribute("uname",n);
13. out.print("<a href='servlet2'>visit</a>");
14. out.close();
15. }catch(Exception e){System.out.println(e);}
16. } }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9. HttpSession session=request.getSession(false);
10. String n=(String)session.getAttribute("uname");
11. out.print("Hello "+n);
12. out.close();

Veda.kotagiriPage 33
UNIT-IV
13. }catch(Exception e){System.out.println(e);}
14. } }

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>s1</servlet-name>
4. <servlet-class>FirstServlet</servlet-class>
5. </servlet>
6. <servlet-mapping>
7. <servlet-name>s1</servlet-name>
8. <url-pattern>/servlet1</url-pattern>
9. </servlet-mapping>
10. <servlet>
11. <servlet-name>s2</servlet-name>
12. <servlet-class>SecondServlet</servlet-class>
13. </servlet>
14. <servlet-mapping>
15. <servlet-name>s2</servlet-name>
16. <url-pattern>/servlet2</url-pattern>
17. </servlet-mapping> </web-app>

Java Database Connectivity with 5 Steps

There are 5 steps to connect any java application with the database using JDBC. These steps are
as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

Veda.kotagiriPage 34
UNIT-IV

1) Register the driver class


The forName() method of Class class is used to register the driver class. This method is used to
dynamically load the driver class.

Syntax of forName() method

1. public static void forName(String className)throws ClassNotFoundException

Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put
vender's Jar in the classpath, and then JDBC driver manager can detect and load the driver
automatically.

Example to register the OracleDriver class


Here, Java program is loading oracle driver to establish database connection.

1. Class.forName("com.mysql.jdbc.Driver");

2) Create the connection object


Veda.kotagiriPage 35
UNIT-IV

The getConnection() method of DriverManager class is used to establish connection with the
database.

Syntax of getConnection() method

1. 1) public static Connection getConnection(String url)throws SQLException


2. 2) public static Connection getConnection(String url,String name,String password)
3. throws SQLException

Example to establish connection with the Oracle database


1. Connection con=DriverManager.getConnection(
2. "jdbc:mysql://@localhost:3306/cse","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement. The object
of statement is responsible to execute queries with the database.

Syntax of createStatement() method

1. public Statement createStatement()throws SQLException

Example to create the statement object


1. Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to the database. T
method returns the object of ResultSet that can be used to get all the records of a table.

Syntax of executeQuery() method

1. public ResultSet executeQuery(String sql)throws SQLException

Example to execute query


1. ResultSet rs=stmt.executeQuery("select * from emp");
2.
Veda.kotagiriPage 36
UNIT-IV
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }

5) Close the connection object

By closing connection object statement and ResultSet will be closed automatically. The
close() method of Connection interface is used to close the connection.

Syntax of close() method

1. public void close()throws SQLException

Example to close connection


1. con.close();

Veda.kotagiriPage 37

You might also like