0% found this document useful (0 votes)
299 views14 pages

Servlet Architecture

Servlet
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)
299 views14 pages

Servlet Architecture

Servlet
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/ 14

SERVLET ARCHITECTURE

 Servlets are grouped under the Advanced Java tree that is


used to create dynamic web applications.
 Servlets are robust, well scalable, and are primarily used in
developing server-side applications.
 Can easily manage/control the application flow.
 Suitable to implement business logic.
 Can effectively balance the load on the server side.
 Easily generate dynamic web content.
 Handle HTTP Request and Response
 Also act as an interceptor or filter for a specific group of
requests.
Types of Servlet
 Generic Servlets: These are those servlets that provide
functionality for implementing a servlet. It is a generic class
from which all the customizable servlets are derived. It is
protocol-independent and provides support for HTTP, FTP, and
SMTP protocols. The class used is ‘javax.servlet.Servlet’ and it
only has 2 methods – init() to initialize & allocate memory to the
servlet and destroy() to deallocate the servlet.
 HTTP Servlets: These are protocol dependent servlets, that
provides support for HTTP request and response. It is typically
used to create web apps. And has two of the most used methods
– doGET() and doPOST() each serving their own purpose.
There are three ways to create a servlet:
 Implementing Servlet Interface
 Extending Generic Servlet
 Extending HTTP Servlet
Components of Servlet Architecture
Servlet Architecture contains the business logic to process all the
requests made by client. Below is the high-level architecture
diagram of servlet. Let’s see in brief, how does each component
add to the working of a servlet.

1. Client
The client shown in the architecture above is the web browser and
it primarily works as a medium that sends out HTTP requests over
to the web server and the web server generates a response based
on some processing in the servlet and the client further processes
the response.
2. Web Server
Primary job of a web server is to process the requests and
responses that a user sends over time and maintain how a web
user would be able to access the files that has been hosted over
the server. The server we are talking about here is a software
which manages access to a centralized resource or service in a
network. There are precisely two types of webservers:
 Static web server
 Dynamic web server
3. Web Container
Web container is another typical component in servlet architecture
which is responsible for communicating with the servlets. Two
prime tasks of a web container are:
 Managing the servlet lifecycle
 URL mapping
Web container sits at the server-side managing and handling all
the requests that are coming in either from the servlets or from
some JSP pages or potentially any other file system.
How does a Servlet Request flow?
Every servlet should override the following 3 methods namely:
1. init(): To initalize/instantiate the servlet container.
2. service(): This method acts like an intermediatory between the
HTTP request and the business logic to serve that particular
request.
3. destroy(): This method is used to deallocate the memory
allocated to the servlet.
These methods are used to process the request from the user.
Following are the steps in which a request flows through a servlet
which can be observed in the architecture diagram:
 The client sends over a request.
 The request is accepted by the web server and forwarded to the
web container.
 In order to obtain the servlet’s address, the web container
traces web.xml file corresponding to the request URL pattern.
 By the time above process takes place, the servlet should have
been instantiated and initialized. The init() method is invoked to
initialize the servlet.
 By passing ServletRequest and Response
object, public service() method is called by the container.
 In the next step, the ServletRequest and ServletResponse objects
are type casted
to HttpServletRequest and HttpServletResponse objects by
the public service() method.
 Now protected service() method is called by the public
service() method.
 The protected service() method dispatches the request to the
correct handler method based on the type of request.
 When servlet container shuts down, it unloads all the servlets
and calls destroy() method for each initialized servlet.
Advantages
 Prime functionality of a servlet is that they are independent of
server configuration, and they are pretty much compatible with
any of the web servers.
 Servlets are also protocol-independent supporting
FTP, HTTP, SMTP, etc. protocols to the fullest.
 Until destroyed manually, servlets can be retained in the
memory helping process several requests over time. Also, once a
database connection is established, it can facilitate process
several requests for a database in the very same database
session.
 Servlets inherit Java’s property of portability and hence are
compatible with nearly any web server.
 Servlets are first converted into byte codes and then executed,
which helps in increasing the processing time.
Disadvantages
 Designing a servlet can be pretty laborious.
 Exceptions need to be handled while designing a servlet since
they are not thread safe.
 Developers may need additional skills to program a servlet.

Servlets - Life Cycle


A servlet life cycle can be defined as the entire process from its
creation till the destruction. The following are the paths followed
by a servlet.
The servlet is initialized by calling the init() method.
The servlet calls service() method to process a client's request.
The servlet is terminated by calling the destroy() method.
Finally, servlet is garbage collected by the garbage collector of
the JVM.
The init() Method
The init method is called only once. It is called only when the
servlet is created, and not called for any user requests
afterwards. So, it is used for one-time initializations, just as
with the init method of applets.
The servlet is normally created when a user first invokes a URL
corresponding to the servlet, but you can also specify that the
servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet
gets created, with each user request resulting in a new thread
that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used
throughout the life of the servlet.
The init method definition looks like this −
public void init() throws ServletException {
// Initialization code...
}

The service() Method


The service() method is the main method to perform the actual
task. The servlet container (i.e. web server) calls the service()
method to handle requests coming from the client( browsers)
and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server
spawns a new thread and calls service. The service() method
checks the HTTP request type (GET, POST, PUT, DELETE, etc.)
and calls doGet, doPost, doPut, doDelete, etc. methods as
appropriate.
Here is the signature of this method −
public void service(ServletRequest request, ServletResponse
response)
throws ServletException, IOException {
}
The service () method is called by the container and service
method invokes doGet, doPost, doPut, doDelete, etc. methods as
appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what
type of request you receive from the client.

The doGet() and doPost() are most frequently used methods with
in each service request. Here is the signature of these two
methods.

The doGet() Method


A GET request results from a normal request for a URL or from
an HTML form that has no METHOD specified and it should be
handled by doGet() method.

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically
lists POST as the METHOD and it should be handled by doPost()
method.

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}
The destroy() Method
The destroy() method is called only once at the end of the life
cycle of a servlet. This method gives your servlet a chance to
close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such
cleanup activities.
After the destroy() method is called, the servlet object is marked
for garbage collection. The destroy method definition looks like
this −

public void destroy() {


// Finalization code...
}

Architecture Diagram
The following figure depicts a typical servlet life-cycle scenario.

First the HTTP requests coming to the server are delegated to


the servlet container.

The servlet container loads the servlet before invoking the


service() method.

Then the servlet container handles multiple requests by


spawning multiple threads, each thread executing the service()
method of a single instance of the servlet.
IN
//EmpForm.html
<!DOCTYPE html>
<html>
<head>
<title>Employee Details</title>
</head>
<body>
<h2>Enter Employee Details</h2>
<form id="employeeForm" action="EmpServlet" method="post">

<label for="empcode">Employee Code:</label>


<input type="text" id="empcode" name="empcode"><br><br>
<label for="empname">Employee Name:</label>
<input type="text" id="empname" name="empname"><br><br>
<label for="desig">Employee Designation:</label>
<input type="text" id="desig" name="desig"><br><br>
<label for="dept">Employee Department:</label>
<input type="text" id="dept" name="dept"><br><br>
<label for="basic">Employee Basic Salary:</label>
<input type="text" id="basic" name="basic"><br><br>

<input type="submit" value="Submit">


</form>
</body>
</html>
//EmpServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmpServlet extends HttpServlet


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

String empcode = request.getParameter("empcode");


String empname = request.getParameter("empname");
String desig = request.getParameter("desig");
String dept = request.getParameter("dept");
String basic = request.getParameter("basic");

PrintWriter out = response.getWriter();


out.println("<html>");
out.println("<head><title>Employee Details</title></head>");
out.println("<body>");
out.println("<h2>Employee Details</h2>");
out.println("<table border=\"1\">");
out.println("<tr><th>Empcode</th><th>Empname</th><th>D
esignation</th><th>Department</th><th>BasicSalary</th></tr>");
out.println("<tr><td>" + empcode + "</td><td>" + empName +
"</td><td>" + desig + "</td><td>" + dept + "</td><td>" + basic +
"</td></tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");
}
}

Database Program
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class EmpServlet extends HttpServlet {


private static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver";
private static final String DB_URL =
"jdbc:mysql://localhost/your_database_name";
private static final String USER = "your_username";
private static final String PASS = "your_password";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
Connection conn = null;
Statement stmt = null;

String empcode = request.getParameter("empcode");


String empname = request.getParameter("empname");
String desig = request.getParameter("desig");
String dept = request.getParameter("dept");
String basic = request.getParameter("basic");

PrintWriter out = response.getWriter();

try {
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER,
PASS);
stmt = conn.createStatement();
String sql;
sql = "INSERT INTO Employee (empcode, empname,
designation, department, basic_salary) VALUES ('" + empcode + "', '"
+ empname + "', '" + desig + "', '" + dept + "', '" + basic + "')";
stmt.executeUpdate(sql);

out.println("<html>");
out.println("<head><title>Employee
Details</title></head>");
out.println("<body>");
out.println("<h2>Employee Details</h2>");
out.println("<table border=\"1\">");
out.println("<tr><th>Empcode</th><th>Empname</th><th
>Designation</th><th>Department</th><th>BasicSalary</th></
tr>");
out.println("<tr><td>" + empcode + "</td><td>" + empname
+ "</td><td>" + desig + "</td><td>" + dept + "</td><td>" + basic +
"</td></tr>");
out.println("</table>");
out.println("</body>");
out.println("</html>");

stmt.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (stmt != null) stmt.close();
} catch (SQLException se2) {
}
try {
if (conn != null) conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
}
}

You might also like