Professional Documents
Culture Documents
J2EE - Module 1
J2EE - Module 1
Servlets
Module 1
Agenda
Introduction to Servlets
5
Objectives
index.html
1. Browser Request 2. Server Finds File
Reads the File
<html> ….
</html>
4. Browser Displays Page 3. Server Response
Database
Notes
Database
Application Client EJB
• ImageSource:
http://image.21tx.com/image/20040830/12533.png
• Servlet and JSP are web tier components that are
running within a web-tier container.
• As you can see from the figure, the servlets and JSP
are web tier components that run within a web-tier.
• The main difference between servlets and JSPs is
that a servlet is written and compiled as a standard
Java class, whereas a JSP is written as a text-based
document, containing both HTML and Java code or
custom tags.
What are Servlets?
MyWebApplication
WEB-INF
web.xml
*.tld
• Files required:
– WelcomeServlet.java
– web.xml
Demo for a Simple Servlet (Contd.).
• An HTTP Servlet that displays a Welcome message
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<web-app>
<display-name>A Small Web Application</display-name>
<servlet>
<servlet-name>MyFirstServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstServlet</servlet-name>
<url-pattern>/welcome.msg</url-pattern>
</servlet-mapping>
</web-app>
Web Container
Web components and their container run on J2EE server
• Provides execution environment for servlets and JSPs of a
web application
• Manages execution of JSP and servlet components for J2EE
applications
1. Suppose you are a web developer working for an Online Movie Service.
You want to use a servlet called MovieServlet so that clients can access the
latest film shows for the day in a particular city from your movie database.
Determine the correct sequence of following steps carried out by
MovieServlet when processing a request from a client
Sl.No Description
1 Check information included in the Http request
2 Access any necessary business components or data storage
3 Set the appropriate Http response parameters
4 Read data submitted by the client
5 Send the response to the client
6 Format the results in a response
Servlet Life Cycle
Life Cycle of a Servlet
Source: http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html
Notes
• When a client makes a request to the servlet, the container
performs the following steps:
• 1.First checks if an instance of the servlet already exists
• 2.If not, the web container
a. Loads the servlet class into the memory
b. Creates an instance of the servlet class
c. Initializes the servlet instance by calling init() method
• 3.Invokes service method, passing request and response
objects
– For every client request the server receives, it creates a new
thread that calls service method
– Depending on type of request, the service method calls
doGet, doPost method
• 4.Finally, container decides when to invoke servlet's destroy()
method to remove it
Servlet interface
• Provides methods that manage the servlet and its communications with
clients
– init(ServletConfig)
Initializes the servlet. Runs once before any requests can be serviced
– service(ServletRequest, ServletResponse)
Processes a single request from the client
– destroy()
This method releases all the resources
– getServletConfig()
Returns a servlet config object and this object contains any initialization
parameters and startup configuration information for this servlet
– getServletInfo()
Returns a string containing information about the servlet, such as its
author, version, and copyright
Lifecycle Methods
• Interaction between a web server, a servlet, and a client
is controlled using the life-cycle methods
• A servlet's life cycle methods are
– init()
– service()
– destroy()
• The init() and destroy() methods will be called only once
during the life time of your Servlet
• The service() and it's broken down methods ( doGet(),
doPost() etc ) will be called as many times as requests
are received for them by the web container
Notes
• Servlets execute in the same address space as
the web server process.
• The web container is responsible for initializing,
running, and destroying each instance of a
running servlet.
• It does this by calling the life-cycle init, service,
and destroy methods defined in the Servlet
interface
Initializing a servlet
• Web container initializes servlet after web container loads and
instantiates servlet class and before it delivers requests from clients
• The init method is invoked only once during servlet's lifetime – when
servlet is first created
• Two versions of init method – one that takes no arguments and one
that takes a ServletConfig object as an argument
– init( ) - use this when your servlet does not need any specific
initialization
– init(ServletConfig) - use this when your servlet needs to check
specific settings before completing initialization
Notes
• The main task of the init method is to allow the
servlet to access deployment-specific initialization
parameters, such as database settings. These
parameters are specified by the application deployer
in the deployment descriptor of the servlet –
web.xml.
• A servlet that cannot complete its initialization
process should throw UnavailableException
Servicing client requests
• Once servlet is loaded and initialized, the servlet is able to handle
client requests
• Web container processes the requests in servlet’s service method
• Every time the server receives an incoming request for a servlet, it
generates a new thread and calls the service method
• The service method then checks the HTTP request type and calls the
appropriate doXXX method
• Syntax: public void service(ServletRequest req, ServletResponse
res)
• Role of service method
– To extract information from the request
– Access external resources
– Populate the response based on that information
Notes
• For HTTP servlets, response is populated by first
retrieving an output stream from the response, then
fill in the response headers, and finally write any
body content to the output stream.
• Usage:
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException
• GET and POST just differ in the way form data is sent
from the browser to the server.
• The method doGet handles data that has been
attached to the url in the form url?(name=value
ampersand)+.
Notes
• With the doPost method, form data comes in
• Through standard input stream.
With Servlets, no need to read in the concatenated string of
parameter names and values. The parsing is all done behind
the scenes. Just call getParameter regardless of how the
form data is actually sent in.
• HttpServletRequest
– The HttpServletRequest object incorporates any
communication from client to servlet
– Provides methods that allow you to retrieve incoming
information
• For example: HTTP request headers, form data, or a
client's hostname
• Methods:
– getWriter
– setContentType
– sendRedirect
Notes
• Other Methods:
– setStatus
– addHeader, setHeader
– getOutputStream, getWriter
– setContentType
– sendError, sendRedirect
Handling Form Data
Handling Form Data
• Simpleform.html
<html>
<head><title>Simple Form</title></head>
<body>
<form method=“post” action=“SimpleFormServlet”>
<h3>Enter user details</h3>
<br>Name: <input type=“text” name=“userName” />
<br>Address: <input type=“text” name=“userAddress” />
<input type=“submit” value=“Submit” />
</form>
</body>
The getParameter() method
• Syntax: public String getParameter(String name)
• Use this method when you are sure the parameter has only one value
<html>
<head><title>Information Details</title></head>
<body>
<form action=“differentCompServlet" method=POST>
<BR>Name: <input type=text name=”name” />
<BR>Address: <textarea name=”address” rows=5 cols=20></textarea>
<BR>State: <select name="state">
<option value="Andhra Pradesh"> Andhra Pradesh </option>
<option value="Karnataka"> Karnataka </option>
<option value="Uttar Pradesh"> Uttar Pradesh</option>
</select>
<BR><BR>Highest Qualification:<BR>
Under Graduate<input type=radio name=qualification value=”UG”>
Post Graduate<input type=radio name=qualification value=”PG”>
<BR><BR>Skills:<BR>
Java<input type=checkbox name=skills value=Java>
Servlets<input type=checkbox name=skills value=Servlets>
JSPs<input type=checkbox name=skills value=JSPs>
EJB 3.0<input type=checkbox name=skills value=EJB>
<BR><BR><input type=submit value=submit><input type=reset>
</form>
</body>
</html>
Methods: getParameterNames() and getParameterValues()
• Syntax: public Enumeration getParameterNames()
– Returns a full list of parameter names as an Enumeration of
String objects, each String containing the name of a request
parameter
– Returns an empty Enumeration if the request has no parameters
• Use this method if a servlet has to get a full list of all request
parameters
• Use this method if a parameter has more than one value. Ex:
checkbox
Example Servlet: Listing different Form Data
• DifferentCompServlet's doPost method retrieves request parameters
using getParameterNames and getParameterValues
while(e.hasMoreElements()) {
String pname = (String) e.nextElement();
String pvalues[] = req.getParameterValues(pname);
pw.println(pname+" : ");
// print parameter values by iterating through array
for(int count = 0; count < pvalues.length; count++)
{
pw.println(pvalues[count]);
}
pw.println("<br>");
}
pw.close(); } }
Demo for Handling Different Form Data
Web Server
Servlet Container
Browser Database
DatabaseServlet
Request
Response
Demo for accessing database
• A servlet to display records from database table
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class DatabaseServlet extends HttpServlet {
Connection con;
PreparedStatement st;
Statement stmt;
ResultSet rs;
public void init(ServletConfig config) throws ServletException {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("Jdbc:Odbc:vdsn2", "scott",
"tiger");
System.out.println("Connected..");
} catch (Exception e) {
System.out.println("Error in connection.."); }}
Demo for accessing database (Contd.).