My Note About Java Servlet 1687330648
My Note About Java Servlet 1687330648
Java Servlet
Servlets
Servlet technology is used to create a web application (resides at server side and
generates a dynamic web page).
There are many interfaces and classes in the Servlet API such as Servlet,
GenericServlet, HttpServlet, ServletRequest, ServletResponse, etc.
What is a Servlet?
o Servlet 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.
CGI technology enables the web server to call an external program and pass
HTTP request information to the external program to process the request. For
each request, it starts a new process.
Disadvantages of CGI
1. If 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.
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:
Servlet API
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.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10.FilterChain
11.ServletRequestListener
12.ServletRequestAttributeListener
13.ServletContextListener
14.ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10.ServletException
11.UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlet Interface
Servlet interface provides commonbehaviorto all the servlets.Servlet interface
defines methods that all servlets must implement.
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.
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.
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface.
such as doGet, doPost, doHead, doTrace etc.
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.
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.
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:
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:
Here, we are going to use apache tomcat server in this example. The steps are
as follows:
The directory structure defines that where to put the different types of files so
that web container may get the information and respond to the client.
The Sun Microsystem defines a unique standard to be followed by all the server
vendors. Let's see the directory structure that must be followed to create the
servlet.
As you can see that the servlet class file must be in the classes folder. The
web.xml file must be under the WEB-INF folder.
2)Create a Servlet
There are three ways to create the servlet.
The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class.
In this example, we are inheriting the HttpServlet class and providing the implementation
of the doGet() method. Notice that get request is the default request.
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
For compiling the Servlet, jar file is required to be loaded. Different Servers
provide different jar files:
2) weblogic.jar Weblogic
3) javaee.jar Glassfish
4) javaee.jar JBoss
Put the java file in any folder. After compiling the java file, paste the class file of
servlet in WEB-INF/classes directory.
The deployment descriptor is an xml file, from which Web Container gets the
information about the servet to be invoked.
The web container uses the Parser to get the information from the web.xml file.
There are many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary
elements to run the simple servlet program.
web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Description of the elements of web.xml file
There are too many elements in the web.xml file. Here is the illustration of some
elements that is used in the above web.xml file. The elements are as follows:
To start Apache Tomcat server, double click on the startup.bat file under apache-
tomcat/bin directory.
ServletRequest Interface
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.
index.html
<form action="welcome" method="get">
Enter your name<input type="text" name="name"><br>
<input type="submit" value="login">
</form>
DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
String name=req.getParameter("name");//will return value
pw.println("Welcome "+name);
pw.close();
}}
RequestDispatcher in Servlet
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.
SendRedirect in servlet
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.
It sends the same request and response objects to It always sends a new
another servlet. request.
It can work within the server only. It can be used within and
outside the server.
Example: Example:
request.getRequestDispacher("servlet2").forward( response.sendRedirect("s
request,response); ervlet2");
1. response.sendRedirect("http://www.javatpoint.com");
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
We can perform some important tasks at the occurrence of these exceptions, such
as counting total and current logged-in users, creating tables of the database at
time of deploying the project, creating database connection object etc.
There are many Event classes and Listener interfaces in the javax.servlet and
javax.servlet.http packages.
Event classes
1. ServletRequestEvent
2. ServletContextEvent
3. ServletRequestAttributeEvent
4. ServletContextAttributeEvent
5. HttpSessionEvent
6. HttpSessionBindingEvent
Event interfaces
The event interfaces are as follows:
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionBindingListener
8. HttpSessionActivationListener
Servlet Filter
A filter is an object that is invoked at the preprocessing and postprocessing of a
request.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.