Java ServletsUnitV
Java ServletsUnitV
Java servlets are server-side programs (running inside a web server) that handle
clients' requests and return a customized or dynamic response for each request.
The dynamic response could be based on user's input (e.g., search, online
shopping, online transaction) with data retrieved from databases or other
applications, or time-sensitive data (such as news and stock prices).
Java servlets typically run on the HTTP protocol. The client sends a request
message to the server, and the server returns a response message.
Explanation
1 ) GET and POST methods take two arguments:
i) HttpServletRequest: HttpServletRequest has methods that let us find out
about incoming information such as FORM data, HTTP request headers, and so
on.
ii) HttpServletResponse: HttpServletResponse has methods that lets us specify
the HTTP response line (200, 404, etc.), response headers (Content-Type, Set-
Cookie, etc.), and, most importantly, lets one obtains a PrintWriter used to send
output back to the client.
2) println() statements generates the desired page.
3 ) The doGet() and doPost() methods throw two exceptions, and they are
included in method declaration.
4 ) doGet() and doPost() are called by the service() method, and sometimes
programmer may want to override service directly.
Servlet Life Cycle
Servlet Life Cycle can be described as a series of steps that a servlet goes
through during its life span from loading to destruction.
1. Servlet class is loaded first when the Web container receives a new
request.
2. Then the web container creates an instance of the servlet. This instance is
created only once in the whole Servlet Life Cycle.
3. The servlet is initialized by the calling init() method.
4. service() method is called by the servlet to process the client's request.
5. Servlet is destroyed by calling the destroy() method.
6. Java Virtual Machine's(JVM) garbage collector clears the
destroyed servlet's memory.
Let us see the signature for each of the methods mentioned above:
init()
Whenever a user invokes the URL associated with the particular servlet,
the init() method is called. It is called only once and not each time there is a
request. An instance of a servlet is created through the init() method. Each user
request creates a new thread catering to GET and POST requests.
public void init(ServletConfig config) throws ServletException{
//initialization code
}
service()
The web container calls the service() method each time there is a new request
to the servlet. This is done by spawning a new thread. This method checks
the HTTP request type, i.e, whether it is a GET, POST, DELETE, etc, and calls the
doGet, doPost, doDelete, etc methods as per the request.
public void service(ServletRequest request, ServletResponse response) throws
ServletException, IOException{
//doGet, doPost, doDelete etc as per request}
destroy()
This method is called just once at the end of the Life Cycle of Servlet. It helps
perform all the clean-up activities including closing database connections,
halting background threads, etc. Then it removes the servlet from the container.
public void destroy (){
//clean-up code
}
Each registered servlet name can have specific initialization (init) parameters
associated with it. Init parameters are available to the servlet at any time; they
are set in the web.xml deployment descriptor and generally used in init( ) to set
initial or default values for a servlet or to customize the servlet’s behavior in
some way.
A servlet uses the getInitParameter( ) method for access to its init parameters:
This method returns the value of the named init parameter or null if it does not
exist. The return value is always a single String. It is up to the servlet to interpret
the value.
The Server
A servlet can find out much about the server in which it is executing. It can learn
the hostname, listening port, and server software, among other things. A servlet
can display this information to a client, use it to customize its behavior based on
a particular server package, or even use it to explicitly restrict the machines on
which the servlet will run.
There are five methods that a servlet can use to learn about its server: two that
are called using the ServletRequest object passed to the servlet and three that
are called from the ServletContext object in which the servlet is executing.
A servlet can get the name of the server and the port number for a particular
request with getServerName( ) and getServerPort( ), respectively:
The Client
For each request, a servlet has the ability to find out about the client machine
and, for pages requiring authentication, about the actual user. This information
can be used for logging access data, associating information with individual
users, or restricting access to certain clients.
mysql>
mysql>
Java Code:
Accessing a Database
// Loading required libraries
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
// Database credentials
static final String USER = "root";
static final String PASS = "password";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" +
"<h1 align = \"center\">" + title + "</h1>\n");
try {
// Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
// Open a connection
Connection conn = DriverManager.getConnection(DB_URL,
USER, PASS);
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
}
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
} catch(SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch(Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if(stmt!=null)
stmt.close();
} catch(SQLException se2) {
} // nothing we can do
try {
if(conn!=null)
conn.close();
} catch(SQLException se) {
se.printStackTrace();
} //end finally try
} //end try
}
}
Web.xml code
....
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
....