Unit 10 1

Download as pdf or txt
Download as pdf or txt
You are on page 1of 15

Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

Unit 10: Servlet Programming


Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a requests coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, we can collect input from users through web page forms, present records from a
database or another source, and create web pages dynamically.
Servlet technology is used to create a web application.
HTTP
HTTP stands for Hyper Text Transfer Protocol.
Following are some of the important properties of HTTP:
1. It is a stateless protocol, meaning that every HTTP request is independent of each
other.
2. It can send data in the request. The server side program reads the data, processes it and
sends the response back. This is the most important feature of HTTP, the ability to send data to
server side program.
Based on how the data is sent in the request, HTTP requests are categorized into several types,
but the most important and widely used are the GET requests and POST requests.
GET
GET is used to request data from a specified resource.
GET is one of the most common HTTP methods.
Note that the query string (name/value pairs) is sent in the URL of a GET request:
/test/demo_form.php?name1=value1&name2=value2
Some other notes on GET requests:
GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests are only used to request data (not modify)
POST
POST is used to send data to a server to create/update a resource.

Compiled By: Tara Bahadur Thapa pg. 1


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

The data sent to the server with POST is stored in the request body of the HTTP request:
POST /test/demo_form.php HTTP/1.1
Host: w3schools.com
name1=value1&name2=value2
POST is one of the most common HTTP methods.
Some other notes on POST requests:
POST requests are never cached
POST requests do not remain in the browser history
POST requests cannot be bookmarked
POST requests have no restrictions on data length
Server Side of the Web Application
The server- side is the heart of any web application as it comprises of the following:
Static resources like HTML files, XML files, Images etc
Server programs for processing the HTTP requests
A runtime that executes the server side programs
A deployment tool for deploying the programs in the server In order to meet the above
requirements, J2EE offers the following:
Servlet and JSP technology to build server side programs
Web Container for hosting the server side programs.
Deployment descriptor which is an XML file used to configure the web application
Web Container
A Web container is the heart of Java based web application which is a sophisticated program that
hosts the server side programs like Servlets.
Once the Servlet programs are deployed in this container, the container is ready to receive HTTP
requests and delegate them to the programs that run inside the container.
These programs then process the requests and generate the responses.
Also a single web container can host several web applications.

Compiled By: Tara Bahadur Thapa pg. 2


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

There are several J2EE Web Containers available in the market. One of the most notable one is
the Apache’s Tomcat container which is available for free of cost.
Structure of a Web Application
For the web container to run the web application, the web application must follow a standard
directory structure within the container. Let’s say we want to build a web application named
myweb. The directory structure for this application must be as shown below:

Where webapps is a standard directory within the web container (Tomcat installation directory).
It is from this directory, you need to start creating the directory structure. Following table lists
the purpose of each directory:

Compiled By: Tara Bahadur Thapa pg. 3


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

Servlet Technology
Servlet technology is a standard J2EE technology used for building dynamic web applications in
Java.
A Servlet is a server side Java program that processes HTTP requests and generates HTTP
response.
Deployment Descriptor
What is Deployment?
Copying the .class file of the Servlet from the current directory to the classes folder of Tomcat
(or any Web server) is known as deployment. When deployed, Tomcat is ready to load and
execute the Servlet, at any time, at the client request.
What is Deployment Descriptor?
As the name indicates, the deployment descriptor describes the deployment information (or Web
Information) of a Servlet. The deployment descriptor is an XML file known as web.xml.
A deployment descriptor is a standard XML file named web.xml that is used by the web
container to run the web applications. Every web application will have one and only one
deployment descriptor (web.xml file).
This file defines the following important information pertaining to a Servlet:
1. Servlet name and Servlet class
2. The URL mapping used to access the Servlet
Let’s assume we wrote a servlet named FormProcesssingServlet in a package named myservlets.
The definition for this servlet in the web.xml will be as shown below:
FormProcessingServlet
myservlets.FormProcessingServlet
The servlet name can be any arbitrary name, but it’s a good practice to have the class name as the
servlet name. However, the servlet class tag must represent the fully qualified name of the servlet
which includes the package name as shown above. This completes Step 1.

Compiled By: Tara Bahadur Thapa pg. 4


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

The next thing we need to define is the URL mapping which identifies how the servlet is
accessed from the browser. For the above servlet, the url mapping will be as shown below:
FormProcessingServlet
/FormProcessingServlet.
Steps for Writing a Servlet
Once Tomcat (Web Container) is installed and configured, you can put it to work. Six steps take
you from writing your servlet to running it.
These steps are as follows:
1. Create a directory structure under Tomcat (Web container) for your application.
2. Write the servlet source code. You need to import the javax.servlet package and the
javax.servlet.http package in your source file.
3. Compile your source code.
4. Create a deployment descriptor.
5. Start the server and deploy the project
6. Call your servlet from a web browser. A servlet can be created by three ways:
By implementing Servlet interface
By inheriting GenericServlet class
By inheriting HttpServlet class
The mostly used approach is by extending HttpServlet because it provides http request
specific method such as doGet(), doPost(), doHead() etc.
So, writing a servlet is very simple. You just have to follow a standard process as shown
below:
 Create a class that extends HttpServlet
 Define methods like init(), doGet() ,doPost() tec.
These three methods are the standard methods for any servlet. These are called as callback
methods that the web container invokes automatically when a HTTP request comes to this
servlet.
For all the GET requests, the web container invokes the doGet() method, and for POST requests
it invokes the doPost() method.
Example: Simple Servlet to display “Testing web page in JSP” in browser
import java.io.IOException;

Compiled By: Tara Bahadur Thapa pg. 5


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

import java.io.PrintWriter;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request,HttpServletResponse response) throws
ServletException, IOException
{
System.out.println("my web app");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<h1> Testing web page in JSP</h1>");
}
}
This is a simple servlet which defined just the doGet() method since we will only send a request
from the browser which is a GET request. This method takes two arguments namely
HttpServletRequest and HttpServletResponse. The former is used to read the data from the
request and the later is used to send the response back to the browser. In this example we only
use the response object to send a greeting message to the browser.
To send a response, we need to do three things as outlined below:
1. Define the type of the response data. This is done using the following statement:
response.setContentType("text/html"); The above line specifies that we are sending HTML
response back.
2. Open a stream/channel to the browser to send the response. This is done using the following
statement: PrintWriter out = response.getWriter();
3. Send the html message to the browser. To send response message to the browser, we use the
println() method as shown below: out.println(" Nepal is a beutiful country! “);
The first two steps are common to any servlet.
// inside web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

Compiled By: Tara Bahadur Thapa pg. 6


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd" version="3.1">
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
</session-timeout>
</session-config>
</web-app>
Reading HTML Form Data
Following are the steps for processing a HTML form using a Servlet
 User fills the data in the html page and submits it.
 The form data will then be sent to Servlet
 Servlet reads the form data, processes it and send a confirmation.
The form data will be sent in the HTTP request object as name value pairs as shown below:
http://localhost:8080/myweb/SomeServlet?name=John&age=20
The servlet then reads the above request data using the HttpServletRequest object as shown
below:
String fn = request.getParameter(“name”);
String age = request.getParameter(“age”);
fn will now have John and age will have 20. The servlet can do whatever it want with the data,
and send a confirmation message back.
Reading Form Data using Servlet
Servlets handles form data parsing automatically using the following methods depending on the
situation

Compiled By: Tara Bahadur Thapa pg. 7


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

getParameter() − You call request.getParameter() method to get the value of a form parameter.
getParameterValues() − Call this method if the parameter appears more than once and returns
multiple values, for example checkbox.
getParameterNames() − Call this method if you want a complete list of all parameters in the
current request.
Example: Calculate the Factorial of a number using servlet
//HTML file
<html>
<head>
<title>My Form</title>
</head>
<body>
<form action = "TU_Question" method = "get">
<label>Enter a Number:</label>
<input type = "text" name = "number"/>
<input type = "submit" value = "Submit"/>
</form>
</body>
</html>
// Java Class
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.ServletException;
public class TU_Question extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");
int num = Integer.parseInt(request.getParameter("number"));
int fact = 1;

Compiled By: Tara Bahadur Thapa pg. 8


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

for(int i = 1; i <= num; i++)


{
fact = fact * i;
}
PrintWriter pw = response.getWriter();
pw.println("<html><body>");
pw.println("<h1>Factorial of "+num+ " is "+fact+"</h1>");
pw.println("</html></body>");
}
}
//In web.xml
<servlet>
<servlet-name>Factorial</servlet-name>
<servlet-class>TU_Question</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Factorial</servlet-name>
<url-pattern>/TU_Question</url-pattern>
</servlet-mapping>
Session Management
Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each
time user requests to the server, server treats the request as the new request. So we need to
maintain the state of an user to recognize to particular user.
HTTP is stateless that means each request is considered as the new request.
Session Tracking Techniques
There are four techniques used in Session tracking:
Cookies
Hidden Form Field
URL Rewriting

Compiled By: Tara Bahadur Thapa pg. 9


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

HttpSession
But here we are just focusing on HttpSession Object
The HttpSession Object
Servlet provides HttpSession Interface which provides a way to identify a user across more than
one page request or visit to a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client and an HTTP
server. The session persists for a specified time period, across more than one connection or page
request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below :-
HttpSession session = request.getSession();
Since the state (data or information) in the session is user specific, the web container maintains a
separate session for each and every user as shown in the following diagram.

If you look at the above figure, every user will have his own session object for storing the state
pertaining to his transaction and all the servlets will have access to the same session. Also notice,
the session objects are present within the container.
These four operations are also called as Session Management operations
1. Create the session
2. Store the data in the session
3. Read the data from the session
4. Destroy the session or invalidate the session.

Compiled By: Tara Bahadur Thapa pg. 10


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

Creating a Session
The servlet API provides us with a class called HttpSession to work with sessions.
To create a session, we do the following:
HttpSession session = request.getSession(true);
The above method returns a new session object if one is not present, otherwise it returns the old
session object that is already created before.
Storing the data in Session
Data in session is stored as key-value pair. The value can be any Java object and the key is
usually a String.
To store the data we use the setAttribute() method as shown below:
session.setAttribute(“price”,new Double(“12.45”));
Reading the data from the Session
To read the data, we need to use the getAttribute() method by passing in the key as shown below
which then returns the value object:
Double d = (Double)session.getAttribute(“price”);
Notice that we need to do proper casting here. Since we stored Double object, we need to cast it
again as Double while reading it.
Destroying the Session
A session is usually destroyed by the last page or servlet in the web application. A session is
destroyed by invoking the invalidate() method as shown below: session.invaliadte()

//Session Example
//index.html
<html>
<head><title>Session </title></head>
<body>
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>

Compiled By: Tara Bahadur Thapa pg. 11


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

</html>
//FirstServlet.java
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
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}
}
//SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet


{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException
{
response.setContentType("text/html");

Compiled By: Tara Bahadur Thapa pg. 12


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

PrintWriter out = response.getWriter();


HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}
}
//web.xml
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
Request Dispatching
Request dispatching is the ability of one servlet to dispatch or delegate the request to another
servlet for processing.
In simple words, let's say we have a servlet A which doesn't know how to completely process the
request. Therefore, after partially processing the request, it should forward the request to another
servlet B. This servlet then does the rest of the processing and sends the final response back to
the browser.

Compiled By: Tara Bahadur Thapa pg. 13


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

The class used for dispatching requests is the RequestDispatcher interface in Servlet API.
This interface has two methods namely forward() and include().
 The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher.
Syntax: public RequestDispatcher getRequestDispatcher(String resource);
Example: RequestDispatcher rd=request.getRequestDispatcher("servlet2"); //servlet2 is the url-
pattern of a servlet rd.forward(request, response);//method may be include or forward The
forward() method This method is used for forwarding request from one servlet to another.
Consider two servlets A and B. Using this method, A gets the request, which then forwards the
request to B, B processes the request and sends the response to the browser. This method takes
HttpServletRequest and HttpServletResponse as parameters.
The include() method With this method, one servlet can include the response of other servlet.
The first servlet will then send the combined response back to the browser. This method also
takes HttpServletRequest and HttpServletResponse as parameters.

forward() vs include() method


To understand the difference between these two methods, let’s take an example: Suppose you
have two pages X and Y. In page X you have an include tag, this means that the control will be
in the page X till it encounters include tag, after that the control will be transferred to page Y. At
the end of the processing of page Y, the control will return back to the page X starting just after

Compiled By: Tara Bahadur Thapa pg. 14


Unit 10: Servlet Programming Java Programming II BIM 5TH SEMESTER

the include tag and remain in X till the end. In this case the final response to the client will be
send by page X.
Now, we are taking the same example with forward. We have same pages X and Y. In page X,
we have forward tag. In this case the control will be in page X till it encounters forward, after
this the control will be transferred to page Y. The main difference here is that the control will not
return back to X, it will be in page Y till the end of it. In this case the final response to the client
will be send by page Y.

Compiled By: Tara Bahadur Thapa pg. 15

You might also like