Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 71

J2EE

Servlets
Module 1
Agenda

Introduction to Servlets

Deploying a Simple Servlet

3 Servlet Life Cycle

4 Handling Form Data

5
Objectives

At the end of this module, you will be able to:

– Describe the role of HTTP Servlet in Web Programming


– Describe and use the Servlet Life Cycle methods
appropriately
– Process parameters from HTML forms
– Establish Database Connectivity through servlets
Introduction to Servlets
Server-side Programming

• Static HTTP transaction - Browser requests for index.html,


and Server responds with HTML file

index.html
1. Browser Request 2. Server Finds File
Reads the File
<html> ….
</html>
4. Browser Displays Page 3. Server Response

HTTP (Hyper Text Transport Protocol) is the protocol


that clients and servers use on the web to communicate
A request is the information that is sent from client to a server.
A response is the information that is sent to client from a server.
A Web Server executes server side programs. These programs exist on
the server and they can interact with other server side resources such as
databases.
The content that is sent by the server may be static or dynamic.
When you access index.html web page that will never change, for
example, if you enter the URL http://www.abc.com/index.html in your
browser, this sends a request to the server whose domain name is
abc.com. The server then will simply fetch the page named index.html as
is and sends it to your browser. This process is known as producing a
static Web page.
Server-side Programming (Contd.).
• Dynamic HTTP transaction - Browser requests
OrderServlet.class, server runs program that creates
HTML, server returns HTML to browser
Web Server
.php /
.cgi
1. Browser Request 2. Executes server program
3. May communicate with Database
<html> ….
4. Creates HTML
</html> 5. Server returns HTML Response
6. Browser Displays Page
5
3

Database
Notes

• The server-side programs with extensions such as .php,


.pl, .cgi, .asp, or .class(a compiled Java Servlet file)
represent programming languages that can run programs
on the server, create HTML "on the fly" and return Html
page on to the browser. This process is known as creating
a dynamic web page.
Web Server

• A computer having server software installed within it which


serves up web pages
• A program that uses client/ server model and World Wide
Web’s Hypertext Transfer Protocol (HTTP)
• Responsible for accepting HTTP requests from clients
(web browsers) and serving HTTP responses which are
web pages such as HTML documents
• Popular web servers
– Apache HTTP Server (Apache)
– Microsoft Internet Information Server (IIS)
– Sun Java System Web Server
Notes

• HTTP (HyperText Transfer Protocol) is the key protocol for


the transfer of data on the web. HTTP is a
request/response standard of a client and a server. A
client is the end-user; the server is the web site.
• HTTP request contains header, a method such as GET or
POST, and request data.
Java server-side web components
• A web component is a software entity that runs on a web server
– Provides it with the capabilities needed for dynamically handling
client requests and generating web presentation content

• The J2EE specification defines two types of web components


– Servlets
– Java Server Pages(JSPs)

Database
Application Client EJB

Web Client JSP / Servlets EJB Database

Client Tier Web Tier Business Tier EIS Tier


Client Environment J2EE Server Database Server

J2EE Application N-Tiered Architecture


Notes

• 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?

• A Java class that runs on a web server and dynamically


handles client requests

• It extends the functionality of a web server by receiving


client requests and dynamically generating a response

• Since servlets are Java-based, they are platform


independent

Servlets use request-response paradigm.


Uses of Servlets

• Processing and/or storing data submitted by an HTML form


– Example: Processing data of a login form

• Providing dynamic content


– Example: Returning results of a database query to the
client

• Managing state information on top of the stateless HTTP


– Example: For an online shopping cart system which
manages shopping carts for many concurrent customers
and maps every request to the right customer
Servlet Architecture Overview
• Java Servlet API are in
packages javax.servlet and
javax.servlet.http Servlet interface
– Provide interfaces and
classes for writing servlets

• All servlets must implement GenericServlet class


Servlet interface
– Defines life-cycle methods
HttpServlet class
• Extend GenericServlet class
– To implement generic services

• Extend HttpServlet class LoginServlet


– To implement HTTP-specific (a user-defined servlet)
services
Notes
• A Servlet, in its most general form, is an instance of a class
which implements the javax.servlet.Servlet interface. Most
Servlets, however, extend one of the standard
implementations of that interface, namely
javax.servlet.GenericServlet and javax.servlet.http.HttpServlet.
• The javax.servlet package contains the Servlet interface,
which declares methods that all servlets must implement either
directly, or by extending a class that implements Servlet.

The Servlet interface declares life-cycle methods that manage


the servlet and its interactions with clients. These are usually
implemented by servlet writers when a servlet is being
developed.
Notes Continued

• The GenericServlet class belongs to the javax.servlet


package.
• If a servlet does not directly implement the Servlet
interface, it must directly extend one of the classes:
GenericServlet or HttpServlet
• The GenericServlet class is used to code generic,
protocol-independent servlets, and the HttpServlet
class enables servlets to operate over HTTP.
Deploying a Simple Servlet
Notes
• To deploy your servlets using Tomcat server, follow the steps
as indicated. Initially, set the environment variables as given
below by going to My Computer -> Right click -> Properties ->
Advanced -> Environment Variables -> System variables
(Caps are the Variable names, followed by is the Variable
Value)
• 1. JAVA_HOME C:\Program Files\Java\jdk1.5.0_02
• This system variable is for location of Java. Find its location
on your system and set it accordingly.
• 2. CATALINA_HOME C:\Program Files\Apache Software
Foundation\Tomcat 5.0
• This system variable is for the location of Tomcat. Find its
location on your system and set it accordingly.
Notes

• 3. CLASSPATH .;C:\Program Files\Apache Software


Foundation\Tomcat 5.0\common\lib\servlet-api.jar;C:\Program
Files\Apache Software Foundation\Tomcat 5.0\common\lib\jsp-
api.jar
• This variable is for the location of all .class files. .(dot) indicates
that you are locating the class files in the current directory. Next
ones are the location of servlet-api.jar and jsp-api.jar files.
• 4. PATH : C:\Program Files\Java\jdk1.5.0_02\bin;
• This is a system variable which you will usually find it in your
system. Locate for the java executables which you will find it in
the bin directory. Add this in the beginning by retaining the
existing values in PATH variable. Please do not delete the pre-
existing values which are already there in this variable value.
Notes

• Note : By default Tomcat would be installed at port number


8080 unless you have changed it to some other port number
like 10000 during installation.
Directory Structure of a Web application

MyWebApplication

WEB-INF

jsp files html files

classes lib tags

web.xml
*.tld

All server-side Library All .tag files


.class files Archive files
Notes

A Web application is a collection of servlets, JSP pages, HTML pages, GIF


files, ...
A Web App is structured as a directory:
MyWebApplication/
contains HTML/jsp/GIF/... files
MyWebApplication/WEB-INF/
contains the deployment descriptor web.xml
MyWebApplication/WEB-INF/classes/
contains servlet class files
(may have subdirectories corresponding to package names)
MyWebApplication/WEB-INF/lib/
contains extra jar files
Demo for a Simple Servlet

• A simple HTTP Servlet that displays a Welcome message


on the web page

• 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.*;

public class WelcomeServlet extends HttpServlet {


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html"); // set header field first
PrintWriter pw = res.getWriter(); // then get writer & write response data
pw.println("<HTML>");
pw.println("<HEAD><TITLE>Welcome</TITLE></HEAD>");
pw.println("<BODY>");
pw.println("<H3>” + “Welcome to Java Servlet Technology!!” + "</H3>");
pw.println("</BODY>");
pw.println("</HTML>");
pw.close(); //closes the writer
}
}
Notes
• This is a simple example of an HTTP servlet that handles GET
and HEAD requests and overrides doGet method. This method
takes in two arguments. The first encapsulates the data from
the client, and is an HttpServletRequest. The second
encapsulates the response to the client, and is an
HttpServletResponse.
• An HttpServletRequest object provides access to HTTP header
data, such as any cookies found in the request and the HTTP
method with which the request was made.
• For responding to the client, an HttpServletResponse object
provides two ways of returning the response data to the user.
You can use the writer returned by the getWriter method or the
output stream returned by the getOutputStream method. Use
getWriter to return text data to the user, and getOutputStream
for binary data.
Notes
• Prior to accessing the Writer or OutputStream, HTTP header
data should be set. The HttpServletResponse class provides
methods to access the header data, such as the content type
and encoding, and content length of the response. After setting
the headers, obtain the writer or output stream and send the
body of the response to the user. Closing the writer or output
stream after sending the response to the client allows the
server to know when the response is complete.
• In the given example servlet, since the doGet method is
returning text to the client, it uses the HttpServletResponse's
getWriter method. It sets the response header field, content
type, before writing the body of the response, and closes the
writer after writing the response.
The Web Deployment Descriptor – web.xml
• An XML file web.xml is a deployment descriptor that describes
– mapping from URIs to application resources
– initialization parameters
– security constraints
– registration of listeners and filters
• Example: web.xml

<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

Fig: J2EE Server and Container Types


Notes
• Imagesource:
http://java.sun.com/j2ee/1.4/docs/tutorial/doc/Overview3.ht
ml
• Tomcat is an example of a container
Role of a Web Container
• Communication Support
– Provides an easy way for servlets to talk to web server
• Lifecycle Management
– Controls lifecycle of servlets
• Multithreading Support
– Automatically creates a new Java thread for every servlet request
it receives
• Declarative Security
– Enables to configure security in an XML deployment descriptor
thereby avoiding hard-coding it in servlet or any other class code
• JSP Support
– Does JSP processing
How web container handles Servlet requests
• Container creates 2 objects on receiving a request for a servlet:
HttpServletRequest and HttpServletResponse
• Finds right servlet based on URL in the request
• Creates a thread for that request
• Passes request and response objects to the servlet thread
• Calls servlet’s service() method
– The service() method in turn calls doGet or doPost based on
type of request (Assume request was an HTTP GET)
– The doGet method generates dynamic page and captures it
in response object
• Converts response object into an HTTP response on completion
of thread
• Sends this response to the client
• Finally deletes the request and response objects
Knowledge Checkpoint

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

• An HTTP servlet's life cycle is controlled by the web


container where it is deployed

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

• Override init method of Servlet interface if you want the servlet to


– Read persistent configuration data
– Initialize resources
– Perform any other one-time activities

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

• Response headers must always be set before the


response has been committed.

• Any attempt to set or add headers after the


response has been committed will be ignored by the
web container
Destroying a Servlet
• Server may unload a servlet instance
– If the servlet has been idle for some time (default is 30
minutes) or
– If the web application is undeployed or
– If server shuts down

• Before it removes the servlet, it calls destroy method only once

• Before servlets get destroyed, this method helps in


– Cleanup operations such as closing database connections
– Halting background threads
– Releasing other resources such as IO streams

• Syntax: public void destroy()


The doGet and doPost methods
• Methods doGet() and doPost() in HttpServlet class receives appropriate
client request, and formats a response using 2 arguments
• An HttpServletRequest object - encapsulates data from the
client
• An HttpServletResponse object - encapsulates response to the
client

• Both these objects are created by the servlet container

• Usage:
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws IOException, ServletException
Notes
• The HttpServletRequest object contains both data
appended to the URL as part of a GET request and
data passed by forms as part of POST requests.

• URL and form parsing is handled automatically by


servlets and the mechanism for retrieving data from
each is the same.

• Upon a client request for a Servlet, the web container


passes the information on to the Servlets service()
method. This method determines the type of request
made (GET, POST, HEAD, ...) and calls the function
doXXX, like doGet, doPost.

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

• The doGet() method


• It contains code that enables the servlet to respond to clients
that make requests via the URL. It reads the client request
information and input parameters. Sets an appropriate
response header, and then Formats the required response.

• The doPost() method


• It contains code that enables the servlet to receive any data
sent by the client as part of an input stream. This is typically
form data and, as it is sent in an input stream rather than a
URL, there is no restriction on the amount of data that can be
sent.
HttpServletRequest interface

• 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 to read parameters from a form


– getParameter(String pname)
– getParameterNames()
– getParameterValues(String pname)
Notes
• The javax.servlet package defines the ServletRequest and
ServletResponse interfcaes. Generic servlet request-
response mechanism are represented by interfaces
ServletRequest and ServletResponse. HttpServletRequest
and HttpServletResponse are the corresponding interfaces
used for HTTP servlets.
• The ServletRequest interface
• Defines a ServletRequest object to supply client request
information to a servlet. Servlet container creates this
object and passes as an argument to servlet’s service
method.
• The ServletResponse interface
• Defines a ServletResponse object to enable a servlet send
a response to a client. Servlet container creates this object
and passes as an argument to servlet’s service method.
Notes
• The HttpServletRequest interface

• Extends the ServletRequest interface. Defines an


HttpServletRequest object to supply client request
information to HTTP servlets. Servlet container creates
this object and passes as an argument to servlet service
methods, such as doGet and doPost.

• The HttpServletResponse interface

• Extends the ServletResponse interface. Designed to


provide HTTP-specific functionality to help HTTP
servlets in sending responses to clients. Servlet
container creates HttpServletResponse object and
passes it as an argument to servlet service methods
such as doGet and doPost
HttpServletResponse interface (Contd.).
• HttpServletResponse
– The HttpServletResponse object incorporates any
communication from servlet to client
– Allows you to specify outgoing information
• For example: response headers and HTTP status
codes
– Also enables you to obtain a PrintWriter object for writing
output back to the client

• Methods:
– getWriter
– setContentType
– sendRedirect
Notes

• Other Methods:
– setStatus
– addHeader, setHeader
– getOutputStream, getWriter
– setContentType
– sendError, sendRedirect
Handling Form Data
Handling Form Data

• Write a Servlet that retrieves form parameters from the HTML


form

• 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)

• To get request parameters sent as an extra information with the request,


invoke getParameter method of ServletRequest (HttpServletRequest
extends ServletRequest)
– Provide parameter name as an argument
– Returns a string that contains URL-decoded value of first occurrence
of that parameter name
• If parameter exists but has no value, then an empty string is
returned
• If parameter does not exist, then null is returned

• Use this method when you are sure the parameter has only one value

• Example: String name = request.getParameter("userName");

For HTTP servlets, parameters are contained in the query


string or posted form data
Example Servlet: Handling Form Data

• SimpleFormServlet's doPost method retrieves request


parameters such as user’s name and address having a
single value from the form
public class SimpleFormServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("userName");
String address = request.getParameter("userAddress");
out.println("<html>");
out.println("<h1>" + “User Details" + "</h1>");
out.println("<p>The Name you entered was: " + name + "</p>");
out.println("<p> The Address you entered was: " + address + "</p>");
}
}
Demo for Handling Simple Form Data

• Demonstrate a SimpleFormServlet with a doPost method that


retrieves request parameters such as user’s name and address
having a single value from the form (getParameter method)
Reason it out

• What difference does it make if SimpleFormServlet used


doGet method and accordingly method=“GET” in the html
form?
Form Data for different HTML Components

• Suppose a Job seeker Company needs basic information


about the user’s name, address, state, highest qualification
and skills comp.html

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

Consider for data having different HTML components


Form Data for different HTML Components (Contd.).
comp.html

<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

• Syntax: public String[ ] getParameterValues(String name)


– Returns an array of String objects containing all values the given
request parameter has
– Returns null if the parameter does not exist
– If the parameter has a single value, the array has a length of 1

• 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

public class DifferentCompServlet extends HttpServlet {


public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
Enumeration e = req.getParameterNames();
// Get enumeration of parameter names

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

• Demonstrate a DifferentFormServlet with a doPost


method that retrieves request parameters of various form
data using getParameterNames and getParameterValues
Using JDBC in a Servlet

• A servlet can retrieve information from a database or


perform update/delete/insert queries to/from a database

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

public void doGet(HttpServletRequest req, HttpServletResponse


res) throws ServletException, IOException {
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
//Displaying records
try {
stmt = con.createStatement();
rs = stmt.executeQuery("select * from books");

pw.println("Displaying Book Records...");


while (rs.next()) {
pw.println("<p>" + rs.getInt(1) + " " + rs.getString(2) + " "
+rs.getString(3));
}
} catch (Exception e) {
System.out.println("Error..." + e);
} } }
Reason it out

• When you use a servlet to interact with database, why is it preferred


to include database connection statements in the init method?

• In the demo example for information retrieval, what would happen if


you you use doPost method instead of doGet method?

• Let us say your servlet class is “DatabaseServlet.java”. How do you


access the servlet through the URL:
http://localhost:10000/ServletsModularization/books.show
Summary

In this module, you were able to:

– Describe the role of HTTP Servlet in Web Programming


– Describe and use the Servlet Life Cycle methods appropriately
– Process parameters from HTML forms
– Establish Database Connectivity through servlets
Quiz
1. The doGet() or doPost() method of a Servlet are
invoked by --------------------
1. init() method
2. service() method
3. destroy() method

• --------------- is the deployment descriptor file for Servlets


1. servlet-config.xml
2. web.xml
3. struts-config.xml
References
1. TutorialsPoint.COM (2012). Servlets Tutorial. Retrieved April 1, 2012
from http://www.tutorialspoint.com/servlets/index.htm

2. Stephanie Bodoff. Oracle Sun Developer Network: JavaServer Pages


Technology. Retrieved April 1, 2012, from,
http://java.sun.com/j2ee/tutorial/1_3-fcs/doc/Servlets.html

3. SkillSoft (2003).Developing a basic HTTP servlet. Retrieved April 10,


2012, from,
http://www.alc.amadeus.com/content/public/alw/skillsoft/cbtlib/73468/7
3473/eng/thin/transcript.html

4. Saravanan Sivaji (2009). Developing a Basic Servlet Program.


Retrieved April 10, 2012, from,http://saravananmtech.wordpress.co
m/2009/04/

5. Javatut99 (1999). Lifecycle of a Servlet. Retrieved April 10, 2012, from,


http://www.iam.ubc.ca/guides/javatut99/servlets/lifecycle/index.html
Thank You

You might also like