Unit 10 1
Unit 10 1
Unit 10 1
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.
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:
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.
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;
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"
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
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;
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.
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>
</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.*;
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.
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.