Advance Java - Servlets
Introduction to Servlets
Servlets are the Java programs that run on the Java-enabled web server or application server. They are used to handle the request obtained from the webserver, process the request, produce the response, then send a response back to the webserver.
Properties of Servlets are as follows:
- Servlets work on the server-side.
- Servlets are capable of handling complex requests obtained from the webserver.
Servlet Architecture is can be depicted from the image itself as provided below as follows:
The Servlet Architecture
The servlet high-level architectural diagram is shown below. Let’s have a look at how each component contributes to the operation of a servlet in more detail.
-
Client: The client in the design above serves largely as a channel, making HTTP requests to the server and then processing the response it receives. The web browser, as shown in the diagram, is our client.
-
Web server: A web server’s major purpose is to process the requests and replies that a user sends over time and to keep track of how a web user may access the files that are housed on the server. The server in question is a piece of software that controls access to a network’s centralized resource or service. Webservers are divided into two categories:
- A static web server
- A web server that is constantly updated
- Web container: Another common component in servlet design is the web container, which handles interaction with the servlets. A web container has two primary functions:
- Servlet lifecycle management
- Mapping of URLs
A web container is a server-side application that manages and handles all requests that come in via servlets, JSP pages, or any other file system.
Why do we need For Server-Side extensions?
The server-side extensions are nothing but the
technologies that are used to create dynamic Web pages. Actually, to
provide the facility of dynamic Web pages, Web pages need a container or
Web server. To meet this requirement, independent Web server providers
offer some proprietary solutions in the form of APIs(Application Programming Interface).
These APIs allow us to build programs that can run with a Web server. In this case, Java Servlet is also one of the component APIs of Java Platform Enterprise Edition which sets standards for creating dynamic Web applications in Java. The Servlet technology is similar to other Web server extensions such as Common Gateway Interface(CGI) scripts.
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. For each request, it starts a new process.
Disadvantages of CGI
There are many problems in CGI technology:
- If the number of clients increases, it takes more time for sending the response.
- For each request, it starts a process, and the web server is limited to start processes.
- It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the Servlet. Threads have 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:
- Better performance: because it creates a thread for each request, not process.
- Portability: because it uses Java language.
- Robust: JVM manages Servlets, so we don't need to worry about the memory leak, gabage collection etc.
- Secure: because it uses java language.
Servlet API
At the center of Servlet technology is Servlet, an interface that all servlet
classes must implement either directly or indirectly. We mostly implement it indirectly when we extend a javax.servlet.GenericServlet or javax.servlet.http.HttpServlet class that implements this interface.
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.
The Servlet interface defines a contract between a servlet and the servlet container. The contract boils down to the promise by the servlet container to load the servlet class into memory and call specific methods on the servlet instance. There can only be one instance for each servlet type in an application.
A user request causes the servlet container to call a servlet’s service method, passing an instance of ServletRequest and an instance of ServletResponse. The ServletRequest encapsulates the current HTTP request so that servlet developers do not have to parse and manipulate raw HTTP data. The ServletResponse represents the HTTP response for the
current user and makes it easy to send response back to the user.
For each application the servlet container also creates an instance of ServletContext. This object encapsulates the environment details of the context (application). There is only one ServletContext for each context.
For each servlet instance, there is also a ServletConfig that encapsulates the
servlet configuration.
Let’s first look at the Servlet interface.The Servlet interface defines these five methods.
void init(ServletConfig config) throws ServletException
void service(ServletRequest request, ServletResponse response)
throws ServletException, java.io.IOException
void destroy()
java.lang.String getServletInfo()
ServletConfig getServletConfig()
init, service, and destroy are lifecycle methods.
The other two methods in Servlet interface are non-life cycle methods:
getServletInfo and getServletConfig.
▪ getServletInfo. This method returns the description of the servlet.
You can return any string that might be useful or even null.
▪ getServletConfig. This method returns the ServletConfig passed by
the servlet container to the init method.
Q.How a HttpServlet Application works ?
Web container is responsible for managing execution of servlets and JSP pages for Java EE application.
When a request comes in for a servlet, the server hands the request to the Web Container. Web Container is responsible for instantiating the servlet or creating a new thread to handle the request. Its the job of Web Container to get the request and response to the servlet. The container creates multiple threads to process multiple requests to a single servlet.
Servlets don't have a main() method. Web Container manages the life cycle of a Servlet instance.
Quick Revision on How a Servlet works
- User sends request for a servlet by clicking a link that has URL to a servlet.
- The container finds the servlet using deployment descriptor and creates two objects :
- a.) HttpServletRequest
b.) HttpServletResponse - Then the container creates or allocates a thread for that request and calls the Servlet's
service()
method and passes the request, response objects as arguments. - The
service()
method, then decides which servlet method,doGet()
ordoPost()
to call, based on HTTP Request Method(Get, Post etc) sent by the client. Suppose the client sent an HTTP GET request, so theservice()
will call Servlet'sdoGet()
method. - Then the Servlet uses response object to write the response back to the client.
- After the
service()
method is completed the thread dies. And the request and response objects are ready for garbage collection.
Q.Explain Life Cycle of a Servlet.
The Servlet container performs two operations in this stage :
- Loading : Loads the Servlet class.
- Instantiation : Creates an instance of the Servlet. To create a new instance of the Servlet, the container uses the no-argument constructor.
- Initializing a Servlet: After the Servlet is
instantiated successfully, the Servlet container initializes the
instantiated Servlet object. The container initializes the Servlet
object by invoking the init(ServletConfig config ) method which accepts ServletConfig object reference as parameter.
The Servlet container invokes the init(ServletConfig config ) method only once, immediately after the init(ServletConfig config ) object is instantiated successfully. This method is used to initialize the resources, such as JDBC datasource.
Now, if the Servlet fails to initialize, then it informs the Servlet container by throwing the ServletException or UnavailableException.
- Handling request: After initialization, the Servlet
instance is ready to serve the client requests. The Servlet container
performs the following operations when the Servlet instance is located
to service a request :
- It creates the ServletRequest and ServletResponse objects. In this case, if this is a HTTP request, then the Web container creates HttpServletRequest and HttpServletResponse objects which are subtypes of the ServletRequest and ServletResponse objects respectively.
- After creating the request and response objects it invokes the service(ServletRequest request , ServletResponse response ) method by passing the request and response objects.
The service() method while processing the request may throw the ServletException or UnavailableException or IOException.
- Destroying a Servlet: When a Servlet container decides to destroy the Servlet, it performs the following operations,
- It allows all the threads currently running in the service method of the Servlet instance to complete their jobs and get released.
- After currently running threads have completed their jobs, the Servlet container calls the destroy() method on the Servlet instance.
After the destroy() method is executed, the Servlet container releases all the references of this Servlet instance so that it becomes eligible for garbage collection.
Q. Types Of Servlets.
1.GenericServlet
In Servlet, GenericServlet is an abstract class. This class implements the servlet, ServletConfig and Serializable interface. This class provides the implementation of most of the basic servlet methods. The protocol of this class is independent as it can handle any type of request. The service() method of this class does the f
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.
2.HttpServlet
HttpServlet is also an abstract class. This class gives implementation of various
service()
methods of Servlet interface.To create a servlet, we should create a class that extends HttpServlet abstract class. The Servlet class that we will create, must not override
service()
method. Our servlet class will override only thedoGet()
and/ordoPost()
methods.The
service()
method of HttpServlet class listens to the Http methods (GET, POST etc) from request stream and invokesdoGet()
ordoPost()
methods based on Http Method type.HttpServlet is an abstract class present in javax.servlet.http package. This class is a subclass of GenericServlet class and used widely to create a servlet. Although HttpServlet extends GenericServlet, still there are much differences between them.
Differences between GenericServlet and HttpServlet
GenericServlet HttpServlet This class is present in javax.servlet package. This class is present in javax.servlet.http package. This class is protocol independent i.e it can handle any type of request. This class is protocol dependent i.e it can handle only http request. This class must override service() method. This class must override atleast one of the provided method such as – doGet(), doPost(), doPut(), doDelete() Using this class we cannot handle cookies. This class is capable to handle cookies. Even though GenericServlet is a nice enhancement to Servlet, it is not something we use frequently, however, as it is not as advanced as HttpServlet. HttpServlet is the real deal and used in real-world applications.Q. Difference between doGet() and doPost() method
doGet() doPost() In this method, data is transferred in headers. In this method data is transferred in body. Less data is transferred. More data is transferred This method provides less security as data is exposed on url bar. This method provides more security as data is not exposed on url bar. We can perform task without using external HTML. We cannot perform task without using external HTML. This method is generally used to retrieve information from server. This method is generally used to send information to server.
Q. Differences between the forward() and sendRedirect() methods.
forward() | sendRedirect() |
---|---|
The forward() method is executed in the server side. | The sendRedirect() method is executed in the client side. |
The request is transfer to other resource within same server. | The request is transfer to other resource to different server. |
It does not depend on the client’s request protocol since the forward ( ) method is provided by the servlet container. | The sendRedirect() method is provided under HTTP so it can be used only with HTTP clients. |
The request is shared by the target resource. | New request is created for the destination resource. |
Only one call is consumed in this method. | Two request and response calls are consumed. |
It can be used within server. | It can be used within and outside the server. |
We cannot see forwarded message, it is transparent. | We can see redirected address, it is not transparent. |
The forward() method is faster than sendRedirect() method. | The sendRedirect() method is slower because when new request is created old request object is lost. |
It is declared in RequestDispatcher interface. | It is declared in HttpServletResponse. |
Signature : forward(ServletRequest request, ServletResponse response) |
Signature: void sendRedirect(String url) |
Sample Code : sendRedirect.
public class RedirectServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter out = res.getWriter();
res.sendRedirect("https://gmail.com");
out.close();
}
}
Sample Code : forward
RequestDispatcher rd = request.getRequestDispatcher("/home.html");
rd.include(request, response);
Example of forwarding and SendRedirect in JSP Servlet:
Which one is good?
Q. Explain MVC(Model-View-Controller) Architecture.
If the system deploys a single component that interacts with the user as well as maintains
the database, then a requirement to support a new type of display or view will
necessitate the redesign of the component. For example , how to provide services to different clients: web browser as a client, mobile as a client, etc.,
a third component that coordinates the first two. These three components are called
the Model, the View, and the Controller, and they form the basis of the MVC pattern.
Figure shows the relationship between the components of the MVC pattern.
Here are the responsibilities of the three MVC components:
• Model—The Model is responsible for keeping the data or the state of the application.
It also manages the storage and retrieval of the data from the data
source. It notifies all the Views that are viewing its data when the data changes.
• View—The View contains the presentation logic. It displays the data contained
in the Model to the users. It also allows the user to interact with the system and
notifies the Controller of the users’ actions.
• Controller—The Controller manages the whole show. It instantiates the Model
and the View and associates the View with the Model. Depending on the application
requirements, it may instantiate multiple Views and may associate them
with the same Model. It listens for the users’ actions and manipulates the Model
as dictated by the business rules.
Q. Describe HttpSession in servlets. What is the purpose of
request.getSession(
false
)?
In web terminology, a session is simply the limited interval of time in which two systems communicate with each other. The two systems can share a client-server or a peer-to-peer relationship. However, in Http protocol, the state of the communication is not maintained. Hence, the web applications that work on http protocol use several different technologies that comprise Session Tracking, which means maintaining the state (data) of the user, in order to recognize him/her.
In order to achieve session tracking in servlets, cookies have been one of the most commonly used tech. However, they have the following disadvantages:
- They can only keep textual information.
- They’re browser dependent. Hence, if the client disables them, your web application can’t make use of them
- Individual cookie can contain not more than 4kb of information
How to create sessions with a unique session id for each user in java servlet.For this, servlets provide an interface called ‘HttpSession’ Interface. The following diagram explains how Http Sessions work in servlets:
Advantages of Http Sessions in Servlet
- Any kind of object can be stored into a session, be it a text, database, dataset etc.
- Usage of sessions is not dependent on the client’s browser.
- Sessions are secure and transparent
Disadvantages of Http session
- Performance overhead due to session object being stored on server
- Overhead due to serialization and de-serialization of data
Example of Session tracking using HttpServlet Interface: In the below code example the setAttribute() and getAttribute() methods of the HttpServlet class is used to create an attribute in the session scope of one servlet and fetch that attribute from the session scope of another servlet.
index.html<head>
<body>
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="submit"/>
</form>
</body>
</html>
// The first servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class First extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try { /*Declaration of the get method*/
response.setContentType("text/html"); // Setting the content type to text
PrintWriter out = response.getWriter();
/*Fetching the contents of
the userName field from the form*/
String n = request.getParameter("userName");
out.print("Welcome " + n); // Printing the username
HttpSession session = request.getSession(); /* Creating a new session*/
session.setAttribute("uname", n);
/*Setting a variable uname
containing the value as the fetched
username as an attribute of the session
which will be shared among different servlets
of the application*/
out.print("<a href='servlet2'>visit</a>"); // Link to the second servlet
out.close();
} catch (Exception e) {
System.out.println(e);
}
}
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
/*Declaration of the get method*/
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session = request.getSession(false);
/*Resuming the session created
in the previous servlet using
the same method that was used
to create the session.
The boolean parameter 'false'
has been passed so that a new session
is not created since the session already
exists*/
String n = (String)session.getAttribute("uname");
out.print("Hello " + n);
out.close();
}
catch (Exception e) {
System.out.println(e);
}
}
Method | Description |
---|---|
public HttpSession getSession() | Gets the HttpSession object. If the request doesn’t have a session associated with it, a new session is created |
public HttpSession getSession(boolean create) | Gets the session associated with the request. If not already present, then a new one is created based on the value of the boolean argument passed into it |
public String getId() | Returns the unique session id |
public long getCreationTime() | It returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. |
public long getLastAccessedTime() | It returns the time when this session was last accessed, measured in milliseconds since midnight January 1, 1970 GMT. |
public long getLastAccessedTime() | It returns the time when this session was last accessed, measured in milliseconds since midnight January 1, 1970 GMT. |
public void invalidate() | Invalidates the session |
Comments
Post a Comment