Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
16 views

Java ServletsUnitV

The document discusses Java servlets, which are server-side programs that handle client requests and return dynamic responses. It covers servlet basics, lifecycle, uses, advantages, structure, retrieving information from requests, and sending responses. Key topics include processing forms, managing state, interfacing with servers and databases, and portability.

Uploaded by

samreen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java ServletsUnitV

The document discusses Java servlets, which are server-side programs that handle client requests and return dynamic responses. It covers servlet basics, lifecycle, uses, advantages, structure, retrieving information from requests, and sending responses. Key topics include processing forms, managing state, interfacing with servers and databases, and portability.

Uploaded by

samreen
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 13

Java Servlets

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.

HTTP Servlet Basics


A servlet is an object that receives a request and generates a response based on
that request.
Servlets are modules that extend request/response-oriented servers, such as
Java enabled web servers.
Servlets are to servers what applets are to browsers. Unlike applets, however,
servlets have no graphical user interface. Servlets can be embedded in many
different servers because the servlet API, which use to write servlets, assumes
nothing about the server's environment or protocol. Servlets have become most
widely used within HTTP servers
The package javax.servlet.http defines HTTP-specific subclasses of the generic
servlet elements, including session management objects that track multiple
requests and responses between the web server and a client.

Uses for HTTP Servlets


1) Processing and Storing: Processing and storing data submitted by an HTML
form.
2) Dynamic Content: Providing dynamic content, e.g., returning the results of a
database query to the client.
3) State Information: Managing state information on top of the stateless HTTP,
e.g., for an online shopping cart system which manages shopping carts for many
concurrent customers and maps every request to the right customer.
For example, a servlet might be responsible for taking data in an HTML order-
entry form and applying the business logic used to update a company's order
database.
Advantages of Servlets
1) Efficient: Threads instead of OS processes, one servlet copy, persistence.
2) Convenient: Lots of high-level utilities.
3) Powerful: Talking to server, sharing data, pooling.
4) Portable: Run on virtually all operating systems and servers,
5) Secure: No shell escapes, no buffer overflows.
6) Inexpensive: Inexpensive plug-ins if servlet support not bundled.
Basic Servlet Structure
A servlet is a small Java program that runs within a Web server. Servlets receive
respond to requests from Web clients, usually across HTTP (HyperText Transfer
Protocol).
Basic steps for writing a Servlet class
Step 1) Implement the Servlet interface available in javax.servlet package
(javax.servlet.Servlet) for HttpServlet, HttpServletRequest and
HttpServletResponse etc.
Step 2) Programmers have to import classes in java.io (for PrintWriter, etc.).
Step 3) The access specifier for the servlet class must be public.
Step 4) Class should extend HttpServlet and override doGet or doPost (or both).
depending on whether the data is being sent by GET or by POST Method.
For example, consider the following code segment.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
// Use "request" to read incoming HTTP headers (for example, cookies)
// and HTML form data (for example, data the user entered and submitted)
// Use "response" to specify the HTTP response line and headers
// (e.g. specifying the content type, setting cookies).
PrintWriter out = response.getWriter();
// Use "out" to send content to browser
}}

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.

The Servlet Life Cycle is as follows:

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
}

Sending html information


A servlet has access to all sorts of information-information about the client,
about the server, about the request, and even about itself. A servlet can do with
that information, by learning how it sets and sends information.
Structure of a Response
An HTTP servlet can return three kinds of things to the client:
1) A single Status Code
2) Any number of HTTP Headers
3) A Response Body
A status code is an integer value that describes, as it would be expected, the
status of the response. The status code can indicate success or failure, or it can
tell the client software to take further action to finish the request. The most
famous status code is probably the "404 Not Found" code, sent by a web server
when it cannot locate a requested URL.
The response body is the main content of the response. For an HTML page, the
response body is the HTML itself. A response body can be of any type and of any
length; the client knows what to expect by reading and interpreting the HTTP
headers in the response.
The HttpServletResponse object is also used to manipulate the HTTP headers of
a response along with sending content back to a client. HTTP response headers
are helpful for informing a client of information, such as the type of content
being sent back, how much content is being sent, and what type of server is
sending the content.
Retrieving Information
To build a successful web application, we often need to know a lot about the
environment in which it is running.we may need to find out about the server
that is executing your servlets or the specifics of the client that is sending
requests. And no matter what kind of environment the application is running in,
we most certainly need information about the requests that the application is
handling.

Getting a Servlet Init Parameter

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:

public String ServletConfig.getInitParameter(String name)

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:

public String ServletRequest.getServerName()


public int ServletRequest.getServerPort()

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.

Getting Information About the Client Machine

A servlet can use getRemoteAddr( ) and getRemoteHost( ) to retrieve the IP


address and hostname of the client machine, respectively:

public String ServletRequest.getRemoteAddr()


public String ServletRequest.getRemoteHost()
Session Tracking
Session tracking is a concept which allows user to maintain a relation between
two successive requests made to a server on the Internet.
When a user requests for a page the server returns that web page to the user.
When the user once again clicks on a new link the server once again sends the
new page that was requested. The server (because of the use of HTTP as the
underlying protocol) has no idea that these two successive requests have come
from the same user. The server is not at all bothered about who is asking for the
pages. All it does it return the page that has been requested. This is exactly what
stateless means. There is no connection between two successive requests on
the Internet.
HTTP is a stateless protocol. This means that if a user inputs some data on a web
page and then goes to another page, the second page does not "know" what
has been done on the first. Session tracking allows the server application to
remember the user's input and carry it from page to page.
A session is some logical task that a user tries to accomplish on a website.
Session information can be stored either in the client or in the server tier, and
the Java. Servlets API enables one to store the session data by using cookies,
rewriting the URL, and using hidden form fields cookies or the session tracking
API provided by the HTTPSession class.
There are four techniques used in session tracking:
1) Cookies
2) Hidden Form Field
3) URL Rewriting
4) HttpSession
1) Cookies: A cookie is a small file or information that a web server may send to
the user's web browser, which in turn saves it to the hard disk. This file contains
an ID that is unique to the computer, so the server can identify the user when
he or she connects to that particular website again.
2) Hidden Form Field: One way to support anonymous session tracking is to use
hidden form fields. As the name implies, these are fields added to an HTML
form that are not displayed in the client's browser. They are sent back to the
server when the form that contains them is submitted. The hidden form fields
with HTML are included like this:
<FORM ACTION="/servlet/MovieFinder" METHOD="POST">
<INPUT TYPE=hidden NAME="zip" VALUE="94040">
<INPUT TYPE=hidden NAME="level" VALUE="expert">
</FORM>
3) URL Rewriting: URL rewriting is another way to support anonymous session
tracking. With URL rewriting, every local URL the user might click on is
dynamically modified, or rewritten, to include extra information. The extra
information can be in the form of extra path information, added parameters, or
some custom, server-specific URL change. Due to the limited space available in
rewriting a URL, the extra information is usually limited to a unique session ID.
One can send parameter name/value pairs using the following format:
URL?namel-valuel &name2=value2&??
3) A Response Body: In this case container creates a session id for individual
user. The container uses this id to identify the particular user. An object of
HttpSession can be used to perform the following task:
1) Bind the objects and
2) View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.
Database Connectivity
To connect the database with servlet make sure apache tomcat must be
installed properly.
Create Database on mysql :
mysql> create database TEST;
Query OK, 1 row affected (0.04 sec)

mysql> use TEST;


Database changed
mysql> create table Employees (
id int not null,
age int not null,
first varchar (255),
last varchar (255)
);
Query OK, 0 rows affected (0.08 sec)

mysql>

mysql> INSERT INTO Employees VALUES (100, 18, 'Aidan', 'butler');


Query OK, 1 row affected (0.02 sec)

mysql> INSERT INTO Employees VALUES (100, 18, 'Scott', 'Tucker');


Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Employees VALUES (100, 18, 'Joey', 'Gomez');


Query OK, 1 row affected (0.01 sec)

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

public class DatabaseAccess extends HttpServlet{

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// JDBC driver name and database URL


static final String JDBC_DRIVER =
"com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/TEST";

// Database credentials
static final String USER = "root";
static final String PASS = "password";

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";

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

// Execute SQL query


Statement stmt = conn.createStatement();
String sql;
sql = "SELECT id, first, last, age FROM Employees";
ResultSet rs = stmt.executeQuery(sql);

// Extract data from result set


while(rs.next()){
//Retrieve by column name
int id = rs.getInt("id");
int age = rs.getInt("age");
String first = rs.getString("first");
String last = rs.getString("last");

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

Now call this servlet using URL http://localhost:8080/DatabaseAccess which


would display following response –
Database Result

ID: 100, Age: 18, First: Aidan, Last: butler


ID: 101, Age: 25, First: Scott, Last: Tucker
ID: 102, Age: 30, First: Joey, Last: Gomez

You might also like