SlideShare a Scribd company logo
1 of 48
Java and J2EE
Java Servlets
What is a Java Servlet?
A java servlet is a server side program that is called by the user interface or another J2EE
component and contains the business logic to process a request
What is Common Gateway Interface(CGI)?
Originally, a server-side program handled client requests by using the Common Gateway
Interface (CGI), which was programmed using Perl. It is the standard for creating dynamic web
pages. It is a part of the web server that can communicate with other programs running on the server.
How CGI woks?
Figure. How CGI works
1. Client sends a request to server
2. Server starts a CGI script
3. Script computes a result for server and quits
4. Server returns response to client
5. Another client sends a request
6. Server starts the CGI script again etc.
What are the disadvatages/drawback of CGI?
• Each time a CGI script is called, a separate process is created
• It was also expensive to open and close database connections for each client request
• CGI programs were not platform independent
• Once CGI program terminates, all data used by the process is lost and can not be used
by the other CGI programs
• Only defines interface, no supporting infrastructure (security, sessions, persistence,
etc.)
1
1
23
4
5
1
23
4
5
Java and J2EE
How Servlet works?
Figure. How Servlet works
1. Client sends a request to server
2. Server starts a servlet
3. Servlet computes a result for server and does not quit
4. Server returns response to client
5. Another client sends a request
6. Server calls the servlet again etc.
What are the advantages of Servlets over CGI?
• Performance is significantly better
2
1
23
4
5
Java and J2EE
• persistence. This means that java servlet remains alive after the request is
fulfilled. A servlet stays in memory, so it doesn’t have to be reloaded each time
• Portable - will run on any J2EE-compliant server
• Platform Independence
Servlets are written entirely in java so these are platform independent.
• Secure
• Full functionality of java class libraries is available to servlet
Explain the Life Cycle of a Servlet?
The javax.servlet.Servlet interface defines the three methods known as life-cycle method. These
are:
init(), service(), destroy() – defined in javax.servlet.Servlet interface
The init() method
When a servlet is first loaded, the init() method is invoked. This allows the servlet to perform
any setup processing such as opening files or establishing connections to their servers. If a
servlet is permanently installed in server, it loads when the server strts to run, otherwise, the
server activates a servlet when it receives the first client request.
Note that init() will only be called only once; it will not be called again unless the servlet has
been unloaded and then reloaded by the server.
3
Java and J2EE
Figure. Servlet Life cycle
What you need to run servlets?
o JDK 1.2 or higher.
o A servlet-compatible webserver. (E.g. Tomcat )
Using Tomcat for Servlet Development
To create servlets, you will need access to a servlet development environment. One such used is
Tomcat. Tomcat is the Servlet Engine that handles servlet requests. Tomcat is open source (and
therefore free). It contains the class libraries, documentation and runtime support that you will
need to create and test servlets. You can download tomcat from jakarta.apache.org.
Installing the Tomcat server
The Java software Development Kit(JDK) should be installed on your computer before installing
tomcat.
Then install Tomcat server. The default location for Tomcat5.5 is
C:Program FilesApache Software FoundationTomcat 5.5
To Start Tomcat
Tomcat must be running before you try to execute a servlet.
Select start | Programs Menu | Apache Tomcat 5.5 | Monitor Tomcat, then a tomcat icon appears
on the right bottom tray of the task bar. Right click on the icon and choose start service.
Test Tomcat
You can test whether
the tomcat is runing or
not by requesting on a
web browser
http://localhost:8080
4
Java and J2EE
Figure: Tomcat start page
Set two environment variables:
Tomcat uses an environmental variable JAVA_HOME to indicate the location of the JDK top-
level directory. You may need to set the environmental variable JAVA_HOME to the top-level
directory in which the Java Development Kit is installed( say C:JDK1.5).
The directory C:Program FilesApache Software FoundationTomcat 5.5commonlib contains
servlet-api.jar. This jar file contains the classes and interfaces that are needed to buils servlet.
To make this file accessible, update your CLASSPATH envirinment variable so that it includes
C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar
Placing the compiled servlet class file in the proper Tomcat directory:
Once you have compiled a servlet, you must enable the tomcat to find it. Copy the servlet class
file into the following directory:
C:Program FilesApache Software FoundationTomcat 5.5webappsservlets-examplesWEB-
INFclasses
Add Servlet Name & mapping to the web.xml :
Add the servlet’s name and mapping to the web.xml file located in the follwing directory.
C:Program FilesApache Software FoundationTomcat 5.5webappsservlets-examplesWEB-
INF
For example assuming the first example, called HelloWorld, you will add the following lines in
the section that defines the servlet.
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
5
Java and J2EE
</servlet>
Next, add the following lines to the section that defines the servlet mappings
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
Follow the same general procedure for all the examples.
Steps involved in building and testing a servlet
1. Create and compile the servlet source code. Then copy the servlet’s class file to the proper
directory, and add the servlet’s name and mappings to the proper web.xml file
2. Start Tomcat
3. Start a Web browser and request the servlet.
Your First Servlet - HelloWorld
Now let's write a simple java servlet that writes "Hello World!" to the browser:
import javax.servlet.*;
import java.io.*;
public class HelloWorld extends GenericServlet {
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException
{
// Set the content type of the response.
resp.setContentType ("text/html");
// Get an output stream object from the response
PrintWriter out = resp.getWriter ();
// Write body content to output stream
// The first part of the response.
out.println ("<html>");
out.println ("<head><title> Test </title></head>");
out.println ("<body>");
// The greeting.
out.println ("Hello World!");
// Last part.
out.println ("</body>");
6
Java and J2EE
out.println ("</html>");
}
}
Explaination:
Here this file should be named as HelloWorld.java.
It is extending GenericServlet. So the related packages are imported.
service() is the method by which we manipulate the client’s request and responses. It has two
arguments. First, req is an object that is implementing the ServletRequest interface and
secondly, resp is an object that is implementing the ServletResponse interface. These are used
to handle the request and responses. Other methods that are usually called to handle data are
doPost, doPut, doTrace, doHead, etc.
It is throwing two exceptions: IOException and ServletException. IOException usually arises
when the servlet is loaded to the web and ServletException can occur anytime. So it has to be
handled.
resp.setContentType("text/html");
This statement sets the MIME header using the method setContentType() in the response.
PrintWriter out=resp.getWriter();
Here we are getting hold of a handle to write into the output stream. You get a handle by using
the method getWriter() which is implemented by the java.io.PrintWriter class.
We write HTML to the output, e.g.,
out.println ("<html>");
out.println ("<head><title> Test </title></head>");
write the greeting
out.println("Hello World ");
Compiling a Servlet
→ Run javac HelloWorld.java from the command line.
HelloWorld.java compiles to HelloWorld.class.
→ Class file should be located in the web application’s classes folder:
C:<tomcat home>webappsservlets-examplesWEB-INFclasses
Adding Servlet Name & mapping to the web.xml
 Consider a Servlet residing in folder
7
Java and J2EE
webappsservlets-examplesWEB-INFclassesHelloWorld.class
 Assign a name to the servlet in web.xml
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>
 Map a servlet to a custom URL
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/servlet/HelloWorld</url-pattern>
</servlet-mapping>
 Start the Tomcat
Tomcat must be running before you try to execute a servlet.
 Run the Servlet using the following URL:
http://localhost:8080/servlets-examples/servlet/HelloWorld
 Tomcat internally maps all URLs starting with /servlet/* to the /WEB-INF/classes
folder.
What is web.xml
The web.xml file specifies various config. parameter such as:
• the name used to invoke the servlet
• description of the servlet
• the class name of the servlet class
Sample file entry
8
Java and J2EE
What
is
Servlet
API
Two packages contain the classes and interfaces that are required to build servlets. These are:
• javax.servlet
• javax.servlet.http
They constitute the Servlet API. These packages are not part of the java core packages. Instead,
they are standard extensions provided by Tomcat.
javax.servlet Package
The javax.servlet package contains a number of classes and interfaces that establish the
framework in which servlet operate. It contains the classes necessary for a standard, protocol-
independent servlet. The following table summarizes the core interfaces that are provided in this
package.
Interfaces
9
Java and J2EE
Interface Description
Servlet Defines methods that all servlets must implement.
ServletConfig
A servlet configuration object used by a servlet container used to pass
information to a servlet during initialization.
ServletContext
Defines a set of methods that a servlet uses to communicate with its
servlet container, for example, to get the MIME type of a file, dispatch
requests, or write to a log file.
ServletRequest Defines an object to provide client request information to a servlet.
ServletRespons
e
Defines an object to assist a servlet in sending a response to the client.
The Servlet interface
All servlets must implement the Servlet interface. It declares the init(), service(), and destroy()
methods that are called by the server during the life cycle of a servlet. The methods defined by
Servlet are
shown
below.
Methods
10
Java and J2EE
The ServletConfig interface
The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The
methods declared by this interface are summarized below.
Methods
The ServletContext Interface
The ServletContext interface enables servlets to obtain information about their environment.
Several of its methods are summarized below.
11
Java and J2EE
Methods
The
ServletRequest Interface
The ServletRequest interface enables a servlet to get information about a client request. Several
of its methods are summarized below.
Methods:
The ServletResponse Interface
12
Java and J2EE
- The ServletResponse interface enables a servlet to formulate a response for a client. Several of
its methods are summarized below.
Methods
Classes
The following table summarizes the core classes that are provided in javax.servlet package.
Class Description
GenericServlet Defines a generic, protocol-independent servlet.
ServletInputStream
Provides an input stream for reading binary data from a client
request, including an efficient readLine method for reading data
one line at a time.
ServletOutputStream Provides an output stream for sending binary data to the client.
ServletException
Defines a general exception a servlet can throw when it
encounters difficulty.
UnavailableException
Defines an exception that a servlet or filter throws to indicate
that it is permanently or temporarily unavailable
The GenericServlet class
The GenericServlet class provides the framework for developing basic servlets. If you are
creating a protocol-independent servlet, you probably want to subclass this class rather than
implement the Servlet interface directly. Note that the service() method is declared as abstract;
this is the only method you have to override to implement a generic servlet. GenericServlet
includes basic implementations of the init() and destroy() methods,
13
Java and J2EE
Reading servlet parameters
The ServletRequest interface includes methods that allow you to read the names and values of
parameters that are included in a client request. We will develop s servlet that illustrate their use.
Example: Shows all the parameters sent to the servlet via POST request
The example contains two files:
• PostParameters.html : An HTML form that sends a number of parameters to the
servlet via post request
• ShowPostParameters.java: A servlet that read the names & values of parameters sent
that are included in post request
PostParameters.html: It defines a table that contains two labels and two text fields. One of the
label is Employee and the other is Phone. There is also a submit button. Notice that the action
parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP
POST request.
<HTML>
<HEAD>
<TITLE>A Show Parameters using POST</TITLE>
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<FORM ACTION="http://localhost/servlets-examples/servlet/ShowPostParameters"
METHOD="POST">
<table>
<tr>
<td><b> Employee </td>
<td><INPUT TYPE="TEXT" NAME="e"></td>
</tr>
<tr>
<td><b> Phone </td>
<td><INPUT TYPE="TEXT" NAME="p"></td>
</tr>
</table>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
Note: Copy the PostParameters.html file under C:<Tomcat-Install-Directory>webappsROOT
ShowPostParameters.java :
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class ShowPostParameters extends GenericServlet
14
Java and J2EE
{
public void service(ServletRequest req,ServletResponse resp)
throws ServletException, IOException
{
// Set the content type of the response.
resp.setContentType("text/html");
// Extract the PrintWriter to write the response.
PrintWriter out = resp.getWriter();
// The first part of the response.
out.println ("<html>");
out.println ("<head><title> Test </title></head>");
out.println ("<body>");
// Now get the parameters and output them back.
out.println ("Request parameters: ");
Enumeration e = req.getParameterNames();
while(e.hasMoreElements())
{
String pname = (String)e.nextElement();
String pvalue = req.getParameter(pname);
out.print(pname + "=" + pvalue);
}
// Last part.
out.println("</body>");
out.println("</html>");
out.close();
}
}
Explaination
• We need to import java.util.Enumeration.
• The service() method is overridden to process client requests
• Whatever parameters were provided are all in the ServletRequest instance.
• We can list these parameters by getting an Enumeration instance from the request by
calling getParameterNames():
Enumeration e = req.getParameterNames();
• The "name" of a parameter is really the string in the name attribute of the tag for the
particular Form element.
15
Java and J2EE
• For example, the name string is ‘e’ below.
Employee: <input type="text" name="e">
• Now, if we want to retrieve the actual string typed in by the user, we use that name in
getParameter():
String whatTheUserTyped = req.getParameter ("e");
javax.servlet.http Package
• Contains number of classes and interfaces that are commonly used by servlet developers
• Its functionality makes it easy to build servlets that work with HTTP requests and
response . i.e. The javax.servlet.http package supports the development of
servlets that use the HTTP protocol
The following table summarizes the core inerfaces that are provided in this package.
Interfaces:
Interface Description
HttpServletRequest
Extends the ServletRequest interface that enables the servlets to
read data from an HTTP request.
HttpServletResponse
Extends the ServletResponse interface that enables servlets to
write data to an HTTP response.
HttpSession
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 HttpServletRequest Interface
The HttpServletRequest interface enables a servlet to obtain information about a client request.
Several of its methods are shown below.
Methods:
16
Java and J2EE
Cookie[]
getCookies()
- Gets the array of cookies found in this request.
String
getMethod()
- Gets the HTTP method (for example, GET, POST, PUT) with which this request was
made.
String
getQueryString()
- Gets any query string that is part of the HTTP request URI.
HttpSession
getSession(boolean create)
- Gets the current valid session associated with this request, if create is false or, if
necessary, creates a new session for the request, if create is true.
The HttpServletResponse Interface
The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
Several of its methods are shown below.
Methods:
void addCookie(Cookie cookie)
- Adds the specified cookie to the response.
The HttpSession Interface
• 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.
• A session usually corresponds to one user, who may visit a site many times. The server
can maintain a session in many ways such as using cookies or rewriting URLs.
Several of its methods are shown below.
Methods
long getCreationTime()
- Returns the time at which this session representation was created, in milliseconds
String getId()
- Returns the identifier assigned to this session.
long getLastAccessedTime()
- Returns the last time the client sent a request carrying the identifier assigned to the session.
17
Java and J2EE
Object getAttribute(String name)
- Returns the object bound with the specified name in this session, or null if no object is bound under
the name.
void setAttribute(Sring name, Object value)
- Binds an object to this session, using the name specified.
Classes
The following table summarizes the core classes that are provided in this package.
The HttpServlet class
• The HttpServlet class extends GenericServlet
• It is commonly used when developing servlets that receive and process HTTP requests
Methods
void doGet(HttpServletRequest req, HttpServletResponse resp)
- Handles an HTTP GET request
void doPost(HttpServletRequest req, HttpServletResponse resp)
- Handles an HTTP POST request
Handling HTTP Requests and Responses
• HttpServlet class provides various methods that handle the various types of HTTP
requests
• A servlet developer typically overrides one of these methods
• These methods are doGet(), doPost() etc
Handling HTTP GET requests
Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a
form on a web page is submitted. The example contains two files.
• ColorGet.html
• ColorGetservlet.java
ColorGet.html: It defines a form that contains a select element and a submit button. Notice that
the action attribute of the form tag specifies a URL. The URL identifies a servlet to process the
HTTP request.
<HTML>
<HEAD>
<TITLE>Handling HTTP GET request</TITLE>
</HEAD>
18
Class Description
Cookie
Creates a cookie, a small amount of information sent by a servlet to a Web
browser, saved by the browser, and later sent back to the server.
HttpServlet Provides methods to handle HTTP requests & responses.
Java and J2EE
<BODY BGCOLOR="#FDF5E6">
<FORM ACTION="http://localhost:8080/servlets-examples/servlet/ColorGetServlet"
METHOD=“GET">
<B>Color:
<select name=“color” >
<option value=“Red” >Red </option>
<option value=“Green” >Green </option>
<option value=“Blue” >Blue </option>
</select><BR>
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
ColorGetServlet.java : In this file doGet() method is overridden to process any HTTP GET
requests that are sent to this servlet. It uses the getParameter() method of HttpServletRequest
to obtain the selection that was made by the user. A response is then formulated.
import java.io.*;
import javax.servlet.*;
import javax.servlet.htto.*;
public class ColorGetServlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
{
// set MIME type
resp.setContentType("text/html");
//Get print writer
PrintWriter out = resp.getWriter();
// Get the value of slection that was made by user
String color = req.getParameter("color");
out.println("The selected color is=" + color);
out.close();
}
}
Handling HTTP POST requests
Same as that of handling HTTP GET request, Note the following changes:
• Replace method=”get” in HTML form to method=”post”
• In servlet, override doPost(), instead of doGet()
•
What is the difference between HttpServlet and GenericServlet?
19
Java and J2EE
GenericServlet is a generalised and protocol independent servlet which defined in javax.servlet
package. Servlets extending GenericServlet should override service() method.
javax.servlet.http.HTTPServlet extends GenericServlet. HTTPServlet is http protocol specific ie
it services only those requests thats coming through http.A subclass of HttpServlet must override
at least one method of doGet(), doPost().
What is the difference between the doGet and doPost methods?
doGet() is called in response to an HTTP GET request. This happens with some HTML FORMs
(those with METHOD=”GET” specified in the FORM tag).
doPost() is called in response to an HTTP POST request. This happens with some HTML
FORMs (those with METHOD="POST" specified in the FORM tag).
Both methods are called by the default implementation of service() in the HttpServlet base class.
Cookie class
What is a cookie?
Cookies are short pieces of data sent by a web servers to the client browser. The cookies are
saved to the hard disk of the client in the form of small text file. Cookies help the web servers to
identify web users and tracking them in the process. A cookie consists of one or more name-
value pairs containing bits of information such as user preferences, shopping cart contents, the
identifier for a server-based session, or other data used by websites.
In servlet, cookies are object of the class javax.servlet.http.Cookie. this class is used to create
cookie, a small amount of information sent by the servlet to a web browser, saved by web
browser and later sent back to the server. The value of cookie can uniquely identify a client, so
cookies are commonly used for session tracking.
A cookie is composed of two pieces. These are cookie name and cookie value. The cookie name
is used to identify a particular cookie from among other cookies stored at client. The cookie
value is data associated with the cookie.
Cookies van be constructed using the following code.
Cookie(String CookieName, String CookieValue)
The first argument is the String object that contains the name of the cookie. The other argument
is a String object that contains the value of the cookie
E.g
Cookie cookie = new Cookie("ID", "123");
In this example, a cookie called ‘ID’ is being created and assigned the value 123.
20
Java and J2EE
A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method
of HttpServletResponse
void addCookie(Cookie cookie)
A servlet can read a cookie by calling the getCookies() method of the HttpServletRequest object.
It returns an array of cookie objects.
Cookie objects have the following methods
Methods
int getMaxAge()
- Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating
the cookie will persist until browser shutdown.
String getName()
- Returns the name of the cookie.
String getValue()
- Returns the value of the cookie.
int getVersion()
- Returns the version of the protocol this cookie complies with.
void setMaxAge(int expiry)
- Sets the maximum age of the cookie in seconds.
void setValue(String newValue)
- Assigns a new value to a cookie after the cookie is created.
Using Cookies
Let us develop a servlet that illustrates how to use cookies.
Example: Program to create and display cookie
The program contains three files as summarized below:
AddCookie.html : Allows a user to specify a name & value for the cookie
AddCookieServlet.java : Processes the submission of AddCookie.html
GetCookieServlet.java : Displays cookie name & values.
AddCookie.html
<html><body><center>
<form method="post"
action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet">
<B> Enter the Name for Cookie:</B>
<input type=text name="name" ><br><br>
Enter the value for a Cookie:
<input type=text name="data" >
<input type=submit value="submit">
</form></body></html>
AddCookieServlet.java
import java.io.*;
21
Java and J2EE
import javax.servlet.*;
import javax.servlet.http.*;
public class AddCookieServlet extends HttpServlet
{
public void doPost(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException
{
// Get paramater from HTTP request
String name=req.getParameter(“name”);
String data=req.getParameter(“data”);
// Create cookie
Cookie cookie=new Cookie(name ,data);
// Add cookie to HTTP response
resp.addCookie(cookie);
// write output to browser
resp.setContentType(“text/html”);
PrintWriter pw= resp.getWriter();
pw.println(“<B>MyCookie has been set to “);
pw.println( “<b>” + name + “ = ” + data);
pw.close(); }}
GetCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetCookieServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// Get cookies from header of HTTP request
Cookie[] cookies=req.getCookies();
//Display these cookies
resp.setContentType("text/html");
PrintWriter pw=resp.getWriter();
pw.println("<b>");
for (int i=0;i<cookies.length;i++)
{
String name=cookies[i].getName();
String value=cookies[i].getValue();
pw.println("Name="+name + "Value= " + value +"<br><br>");
}
pw.close();
}
}
22
Java and J2EE
Disadvantages of cookies
1. Cookies exist as plain text on the client machine and they may pose a possible security risk as
anyone can open and tamper with cookies.
2. Users can delete a cookies.
3. Users browser can refuse cookies,so your code has to anticipate that possibility.
Session Tracking
Cookies are stored on client side where as sessions are server variables.Sessions grew up from
cookies as a way of storing data on the server side, because the inherent problem of storing anything
sensitive on clients' machines is that they are able to tamper with it if they wish.
What is session?
HTTP is a stateless protocol, each request is independent of the previous one. However in some
applications, it is necessary to save state information so that information can be collected from
several interactions between a browser and a server. Sessions provide such a mechanism.
The session is an object used by a servlet to track a user's interaction with a Web application
across multiple HTTP requests. The session is stored on the server.
A java servlet is capable of tracking sessions by using HttpSession interface. An object that
implements this interface can hold information for one user session between requests. A session
can be created via getSession() method of HttpServletRequest. An HttpSession object is
returned
E.g.
HttpSession session = req.getSession(true);
This method takes a boolean argument. true means a new session shall be started if none exist,
while false only returns an existing session. The HttpSession object is unique for one user
session.
You can add data to an HttpSession object with the setAttribute() method. The method requires
two arguments. The first argument is the String object that contains the name of the attribute.
The other argument is an object binded with value
void setAttribute(Sring name, Object value)
This method binds the binds the specified object value under the specified name.
To retrirve an object from session use getAttribute(). This method requires one argument that
contains the name of the attribute whose value you want to retrive.
Object getAttribute(String name)
This method returns the object bound under the specifed name
You can also get the names of all of the objects bound to a session with getAttributeNames()
Enumeration getAttributeNames()
23
Java and J2EE
This returns an Enumeration containing the names of all objects bound to this session as String
objects or an empty Enumeration if there are no bindings.
The following servlet illustrate how to use session state.
Example: Program to create a session and display session information such as current date and
time and the date and time the page was last accessed.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DateServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//Get the HTTP Session object
HttpSession hs = req.getSession(true);
// Display the date/time of last access
Date date = (Date)hs.getAttribute(“date”);
if(date != null)
{
out.println(“Last access: " + date + "<br>");
}
// Display current date/time:
date = new Date();
hs.setAttribute(“date”,date);
out.println(“Current date :" + date);
}
}
Explaination: The getSession() method gets the current session. A new session is created if one
does not already exist. The getAttribute() method is called to obtain the object that is bound to
the name “date”. That object is a Date object that encapsulates the date and time when this page
was last accessed.( ofcourse there is no such binding when the page is first accessed). A Date
object encapsulating the current date and time is created. The setAttribute() method is called to
bind the name “date” to this object.
Output: When the web page is accessed first time. A session is created.
What is the difference between session and cookie?
24
Java and J2EE
1) Sessions are stored in the server side whereas cookies are stored in the client side
2) Session should work regardless of the settings on the client browser. even if users decide to
forbid the cookie (through browser settings) session still works. There is no way to disable
sessions from the client browser.
3) Session and cookies differ in type and amount of information they are capable of storing.
javax.servlet.http.Cookie class has a setValue() method that accepts Strings.
javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the
name and java.lang.Object which means that HttpSession is capable of storing any java
object. Cookie can only store String objects.
What are GET and POST?
o When Form data is sent by the browser, it can be sent in one of two ways:
(1) using the GET method and (2) using the POST method.
o In the GET method, the form data (parameters) is appended to the URL, as in:
http://localhost:8080/servlets-examples/servlet/ColorGetServlet?name=girish
Here, the text field contains girish.
o In the POST method, the browser simply sends the form data directly.
o When you create an HTML form, you decide whether you want to use GET or
POST.
o When you use GET, the doGet() method of your servlet is called, otherwise the
doPost() method is called.
o The standard practice is to use POST, unless you need to use GET.
Exercises
Exercise1
Develop a servlet to accept user name from an HTML form and display a greeting message.
HTML File
<html>
<body bgcolor=blue>
<form action="http://localhost:8080/servlets-examples/servlet/GreetingServlet " method="post">
<center><h3><font color=”red”>Enter Your Name</font> </h3>
<input type="text" name="name">
<br><br>
25
Java and J2EE
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</center>
</form>
</body>
</html>
Servlet file
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
IOException, ServletException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
String name = req.getParameter(“name”);
out.println(“<html><title>Greeting Message</title></head>”);
out.println(“<body bgcolor=wheat><h2>”);
out.println(“ Hello ”+name+”, How are you?”);
out.println(“</h2></body></html>”);
out.close();
}
}
Exercise2
Develop a simple web application on a Tomcat server that includes an HTML page that
takes user name from the clients and submits the request to a java servlet. The servlet
validates the request:
a) If the input is empty, it displays a page to report an error
b) If the input is valid, it displays greeting message to the user
26
Java and J2EE
HTML File
<html>
<body >
<form action="http://localhost:8080/servlets-examples/servlet/GreetingServlet " method="post">
<center><h3><font color=”red”>Enter Your Name</font> </h3>
<input type="text" name="name">
<br><br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</center>
</form>
</body></html>
Servlet file
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class GreetingServlet extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException, ServletException
{
resp.setContentType("text/html");
PrintWriter out=resp.getWriter();
out.println("<html><title>Greeting Message</title></head>");
out.println("<body bgcolor=wheat><h2>");
// read the name parameter value
String name = req.getParameter("name");
// request.getParameter() returns the value of "" (empty string) if the text field was blank
// and trim() method is used to remove the blank spaces from both ends of the empty string
if(name.trim().equals(""))
{
out.println(" Error: Missing name ");
27
Java and J2EE
}
else
{
out.println(" Hello " +name+", How are you?");
}
out.println("</h2></body></html>");
out.close();
}
}
Review Questions
Q. What is java servlet? What are the advatages of servlet over traditional CGI?
Q. Compare servlet with traditional CGI
Q. How servlet works?
Q. Explain the life cycle methods of a servlet.
Q. Explain how to setup tomcat for servlet development
Q. What are the general steps involved in building and testing a servlet
Q. What are the classes and interfaces contained in the javax.servlet package?
Q. Explain the following interfaces and their methods provided in the javax.servlet package
i) Servlet ii) ServletConfig iii) ServletContext iv) ServletRequest v) ServletResponse
Q. Explain with example how to read parameters in a servlet?
or
Write a servlet program to accept Employee name and phone from an HTML form and display
them in a web page by passing parameters.
or
How does a servlet read data entered in an HTML form?
or
Write a simple application in which the HTML form can invoke a servlet
28
Java and J2EE
Q. What are the classes and interfaces contained in the javax.servlet.http package?
Q. Explain the following interfaces and their methods provided in the javax.servlet.http package
i) HttpServletRequest ii) HttpServletResponse iii) HttpSession
Q. Write a servlet program that handles HTTP GET request containing data that is supplied by
the user as a part of the request.
Q. Explain how servlet deals HTTP Get and Post requests with an example
Q. What are cookies? How java servlet support cookies? Explain with example
Q. Develop a java servlet to create and display cookie
Q. Write a servlet that will send a cookie containing your name to the client. Then invoke the
servlet, find and view the cookie file and note its contents.
Q. What is the use of session tracking? How java servlet support the session tracking?
explain with example
Q. What is the difference between session and cookie?
Q. Write a servlet that will read the name value from the following form. If the name is non-
blank, the servlet should bind it to the session and replay with “Hello <name>”. If the name is
blank, the servlet should look for a name previously bound to the session and replay with that
instead (if it exists).
<form method=”post” action=”/hello”>
Name: <input type="text" name="name">
<input type="submit" value="Submit">
</form>
Servlet file: hello.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class hello extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException, ServletException
{
29
Java and J2EE
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
//Get the HTTP Session object
HttpSession hs = req.getSession(true);
// Get the value of the name entered in text field
String name=req.getParameter("name");
// Get the object bound with the specified name in this session, if it exists
String sname = (String)hs.getAttribute("name");
// if name is non blank bind it to the session otherwise display the object bound to the
// specified name
if(sname == null)
{
hs.setAttribute("name",name);
out.println(" Hello " + name );
}
else
{
out.println("Hello :" + sname);
}
}
}
Q. Write a servlet that will process the HTTP request coming from the following form. The
servlet should obtain the values of the two fields. Then display their sum, if both are numeric
or zero otherwise.
<form method=”post” action=”/summation”>
A: <input type="text" name="value1"><br>
B: <input type="text" name="value2">
<input type="submit" value="Add">
</form>
Servlet file: summation.java
import java.io.*;
30
Java and J2EE
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class summation extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse resp)
throws ServletException, IOException
{
// set MIME type
resp.setContentType("text/html");
//Get print writer
PrintWriter out = resp.getWriter();
// read the values of parameters
String v1 = req.getParameter("value1");
String v2 = req.getParameter("value2");
// convert the parameter values in to integer fromat
int value1=Integer.parseInt(v1);
int value2=Integer.parseInt(v2);
int sum=0;
// verify whether the values of the fields are numeric, if yes add the values and print sum
// otherwise output sum as zero
if(value1 > 0 && value2 >0)
{
sum=value1+value2;
out.println("Sum =" + sum);
}
else
{
out.println("sum=0");
}
}
31
Java and J2EE
}
Q. Write a Servlet program that takes your name and address from an HTML form and displays
it
Java Server Pages(JSP)
What is JSP?
- Java Server Page(JSP) is a server side program that is similar in design & functionality to a java
servlet
- JavaServer Pages is the Java 2 Platform, Enterprise Edition(J2EE) technology for building
applications for generating dynamic web content
How JSP differs from Java servlet?
or
Compare JSP with Java servlet
• A Java Servlet is written using the Java Programming Language and responses are
encoded as an output String object that is passed to the println() method. The output
String object is formatted in HTML,XML or whatever formats are required by the client.
i.e. In Servlets you need to have lots of println statements to generate HTML.
E.g.
out.println("<HTML><BODY>");
out.println("<H2>Welcome to my servlet page.</H2>");
out.println("</BODY></HTML>");
32
Java and J2EE
• In contrast, JSP is written in HTML,XML or in the client’s format that is interpersed
with scripting elements, directives and actions comprised of Java Programming language
and JSP syntax
i.e. JSPs are essentially an HTML page with special JSP tags embedded. These JSP tags
can contain Java code.
E.g.
• Servlet is written in java lang,
• Whereas jsp contains both jsp tags and html tags. JSP offers basically the same features
found in java servlet because a JSP is converted to a Java servlet the first time that a
client requests the JSP.
• Servlet is a java class, So for every change, we have to compile the code to reflect the
change.Mainly using for writing business logics (i.e. functional design)
• JSP is a file, It’s automatically converted into a servlet on deploying. We can't compile
it explicitly, the changes will get reflect by saving the file. Its mainly used for
presentation of data (i.e. web page design(look and feel))
How Does JSP work?
Or
33
Java and J2EE
Explain the JSP architecture?
1. The user goes to a web site made using JSP. The user goes to a JSP page (ending with
.jsp).
The web browser makes the request via the Internet.
2. The JSP request gets sent to the Web server.
3. The Web server recognises that the file required is special (.jsp),therefore passes the JSP
file to
the JSP Servlet Engine.
4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7.
5. The next step is to generate a special Servlet from the JSP file. All the HTML required is
converted to println statements.
6. The Servlet source code is compiled into a class.
7. The Servlet is instantiated,calling the init and service methods.
8. HTML from the Servlet output is sent via the Internet.
9. HTML results are displayed on the user's web browser.
What are the advantages of JSP?
34
Java and J2EE
• Content and display logic are separated
• Recompile automatically when changes are made to the source file
• Platform-independent
Explain the Life Cycle methods of JSP?
Overall, the request-response mechanism and the JSP life cycle are the same as those of a
servlet. There are three methods that are automatically called when a JSP is requested & when
the JSP terminates normally.
These are:
• jspInit()
• service()
• jspDestroy()
• The jspInit() method is identical to init() method in a java servlet and executed first after the
JSP is loaded. It is used to initialize objects and variables that are used throughout the life of
the JSP.
• service() is the JSP equivalent of the service() method of a servlet class. The server calls the
service() for each request, passing it the request and the response objects
• The jspDestroy() method is identical to the destroy() method in a java servlet. It is
automatically called when the JSP terminates. It is used for clean up where resources used
during the execution of the JSP are released, such as disconnecting from a database.
What you need to build and test Java Server Page?
• JDK 1.2 or higher.
• JSP enabled server installed. E.g Tomcat JSP Container
Explain the method of deployment of JSP with the Tomcat
• A JSP page can be as simple as an HTML page with a .jsp extension rather than .htm
or .html
• Place any new JSP files in the “webapps/ROOT” directory under your installed Tomcat
directory.
For example, to run “myfirst.jsp” file, copy the file into the “webapps/ROOT” directory and
then open a browser to the address:
35
Java and J2EE
http://localhost:8080/myfirst.jsp
This will show you the executed JSP file.
JSP Tags
- A JSP program consists of a combination of HTML tags and JSP tags.
- JSP tags define java code that is to be executed before the output of the JSP program is sent
to the browser.
- A JSP tag begins with <% , which is followed by java code, and ends with %>
- JSP tags are embedded into HTML component of s JSP program and are processed by a JSP
virtual engine such as Tomcat.
There are five types of JSP tags:
1. Comment tag
2. Declaration tag
3. Directive Tag
4. Expression tag
5. Scriptlet tag
Comment tag: Describes the functionality of statements that follow the comment tag.
Syntax:
<%-- comment --%>
Example:
<%-- This JSP comment part will not be included in the response object --%>
Declaration tag: This tag allows the developer to declare variables , objects and methods that
will be used in Java Server Pages.
Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration.
Syntax :-
<%! declaration %>
Examples
<%! int var = 1; %>
<%! int x, y ; %>
<%!
private int counter = 0 ;
private String get Account ( int accountNo) ;
36
Java and J2EE
%>
Directive Tag
A directive tag commands the JSP virtual engine to perform a specific task such as importing a
java packages required by objects and methods used in a declaration statement.
Syntax of JSP directives is:
<%@directive attribute="value" %>
There are three directives:
• <%@ page ... %> specifies information that affects the page
• <%@ include ... %> includes a file at the location of the include directive (parsed)
• <%@ taglib ... %> allows the use of custom tags in the page
Examples:
<%@ page import = “java.util.*” %> : imports the java.util package
<%@ include file = “keogh/books.html %> : includes books.html file located in the the
keogh directory
<%@ taglib uri = “myTags.tld” %> : loads the myTags.tld library
Expression tag: An expression tag contains a expression that is evaluated, converted to a
String to get dipslayed
Syntax is as follows
<%= expression %>
Example to show the current date and time.
<%= new java.util.Date() %>
Translated to
out.println(new java.util.Date() )
Note: You cannot use a semicolon to end an expression
Scriptlet tag: We can embed any amount of java code in the JSP scriplets.
Syntax :
<%
//Java codes
%>
For example, to print a variable.
<%
String username = “visualbuilder” ;
37
Java and J2EE
out.println ( username ) ;
%>
Develop a JSP page that displays the current date and time
Type the code below into a text file. Name the file Date.jsp. Place this in the correct directory on
your Tomcat web server and call it via your browser.
Date.jsp
<html>
<body>
<center>
<h3>Today is:
<%= new java.util.Date() %>
</h3>
</center>
</body>
</html>
Variables and objects
With JSP declarations, we can declare variables that will be used later in the JSP expressions or
scriplets.
Example: A JSP program that declares and uses a variable
var.jsp
<html>
<head>
<title>My first JSP page
</title>
</head>
<body>
<%! int age = 29 %>
<p> Your age is : <%= age %></p>
38
Java and J2EE
</body>
</html>
Example: Declaring multiple variables within a single JSP tag
<html>
<head>
<title>JSP programming
</title>
</head>
<body>
<%!
int age = 29 ;
float salary;
int empnumber;
%>
</body>
</html>
Example: Declaring objects and arrays within a single JSP tag
<html>
<head>
<title>JSP programming
</title>
</head>
<body>
<%!
String name ;
String[ ] Telephone={ “201-555-1212”, “201-555-4433”};
String Company = new String();
39
Java and J2EE
Vector Assignments = new Vector();
int[ ] Grade = { 100,82,93};
%>
</body>
</html>
Methods
Example: Defining and calling methods
<html>
<head>
<title> JSP programming
</title>
</head>
<body>
<%!
int curve(int grade)
{
return (10+grade);
}
%>
Your curved grade is : <%= curve(80) %>
</body></html>
Control statements
The primary method of flow control provided by JSP for designers are :
• if/else statements.
• switch statements
These statements can check for something, such as the existence of a variable, and control what
is output based on what it finds. Take a look at the following code:
Example: JSP program using an if statement and a switch statement
<html>
<head>
<title> JSP programming</title>
40
Java and J2EE
</head>
<body>
<%! int grade=70; %>
<% if (grade >69) { %>
<p> You passes! </p>
<%} else { %>
<p> Better luck next time. </p>
<% } %>
<% switch(grade) {
case 90: %>
<p> Your final grade is a A</p>
<% break;
case 80: %>
<p> Your final grade is a B</p>
<% break;
case 70: %>
<p> Your final grade is a C</p>
<% break;
case 60: %>
<p> Your final grade is an F</p>
<% break;
}
%>
</body>
</html>
Note: The brackets ({}) are what contain the information relating to the appropriate if or else
and switch condition. It seems odd in this case because the JSP scriptlet elements are separating
the JSP code with the normal HTML code. So the start bracket is in the first JSP scriptlet:
{ %>
and the end bracket is in another, with the output HTML in between:
} %>
The HTML in between will not be included in the HTML page output if the if or else and
switch statement it belongs to is not the correct one. Only one, if or else and switch case,
can be output.
Loops
Example: Using the for loop, while loop and the do..while loop to load HTML tables
<html>
41
Java and J2EE
<head>
<title> JSP programming</title>
</head>
<body>
<%! int[ ] Grade={100,82, 93};
int x=0;
%>
<TABLE>
<TR>
<TD> First </TD>
<TD> Second </TD>
<TD> Third </TD>
</TR>
<TR>
<% for (int i=1;i<3;i++) { %>
<TD> <%= Grade[i] %> </TD>
<% } %>
</TR></TABLE>
<TABLE>
<TR>
<TD> First </TD>
<TD> Second </TD>
<TD> Third </TD>
</TR>
<TR>
<% while (x<3) { %>
<TD> <%= Grade[x] %> </TD>
<% x++;
} %>
</TR>
</TABLE>
<TABLE>
<TR>
<TD> First </TD>
<TD> Second </TD>
<TD> Third </TD>
</TR>
<TR>
<% x=0;
do { %>
<TD> <%= Grade[x] %> </TD>
<% x++;
} while (x<3); %>
</TR></TABLE></BODY></HTML>
Request String
42
Java and J2EE
Retrieving the data (Request string) posted to a JSP file from HTML file is one of the most
common functions in JSP page. Data(request string) is sent in a GET or POST request. . In a
GET request the user request string consists of the URL and the query string(the data following
the question mark on the URL. Here is an example of request string.
http://www.jimkeogh.com/jsp/myprogram.jsp? Fname=”Bob”&lname=”smith”
Retrieving the value of a specific field:
The JSP program needs to parse this query string to extract the values of the fields that are to be
processed by your JSP program.
You can parse the query string by using the methods of the JSP request object.
The getParameter() is the method used to parse a value of a specific field. getParameter()
receives one argument, which is the name of the field whose value you want to receive.
Example: Let us say you want to retrieve the value of the fname filed and the value of the lname
filed in the request string.
Here are the statements that you will need in your JSP
program.
<! String Firstname = request.getParameter(fname);
String Lastname = request.getParameter(lname);
%>
In the above example, the first statement used the getParameter() method to copy the value of
the fname from the request string and assign that value to the Firstname string object. Likewise
the second statement performs a similar function.
Retrieveing a value from a multivalued filed
Retrieveing a value from a multivalued filed such as selection field shown in the figure can be
very tricky since there are multiple instances of the field name, each with different value
The getParameterValues() method is designed return multiple values from the field specified as
an argument to the getParameterValues()
Example:
<% String[ ] Email=request.getParameterValues(“EMAILADDRESS”]; %>
<p><%= EMAIL[0] %></p>
43
Java and J2EE
<p><%= EMAI[1] %></p>
The name of the selection field is EMAILADDRESS, the values of which are copied into an
array of String objects called EMAIL. Elements of the array are then displayed in JSP expression
tag.
Retrieving all field (parameter) names
You can parse field names by using the getParameterNames() method. This method returns an
enumeration of String objects that contain the field names in the request string. Later you can use
the enumeration extracting methods ( such as nextElement(), hasMoreElements()) to copy the
filed names to variables within your JSP progra.
Write a JSP program which displays the first name and last name entered by the user from
an HTML file
HTML file
<HTML>
<HEAD>
<TITLE>Handling HTTP GET request</TITLE>
</HEAD>
<BODY >
<form method="get" action="http://localhost:8080/showname.jsp">
First Name<INPUT TYPE="TEXT" name="fname"><br>
Last name<INPUT TYPE="TEXT" name="lname">
<INPUT TYPE="SUBMIT" VALUE="Submit">
</FORM>
</BODY>
</HTML>
<html><body><center>
JSP file:
<html>
<body>
<%
String FirstName = request.getParameter("fname");
String LastName = request.getParameter("lname");
out.println("First Name="+FirstName+"<br>");
out.println("Last Name="+LastName);
%>
</body></html>
Implicit objects
The Objects available in any JSP without any need for explicit declarations are implicit objects.
These predefined implicit objects are available in the expressions and scriplets of any JSP
document. They are:
44
Java and J2EE
out: This object is instantiated implicitly from JSP Writer class and can be used for displaying
anything within delimiters.
For e.g. out.println(“Hi Buddy”);
request:
It is also an implicit object of class HttpServletRequest class and using this object request
parameters can be accessed.
For e.g. in case of retrieval of parameters from last form is as follows:
request.getParameters(“Name”);
Where “Name” is the form element.
response:
It is also an implicit object of class HttpServletResponse class and using this object response(sent
back to browser) parameters can be modified or set.
For e.g. in case of setting MIME type.
response.setContentType(“text/html”);
session:
Session object is of class HttpSession and used to maintain the session information. It stores the
information in Name-Value pair.
For e.g.
session.setValue(“Name”,”Jakes”);
session.setValue(“Age”,”22”);
Cookies
45
Java and J2EE
Example1 : Creating a cookie
<html>
<head>
<title> JSP Programming </title>
</head>
<body>
<%! String MyCookieName="UserID";
String MyCookieValue="JK1234";
Cookie cookie=new Cookie(MyCookieName,MyCookieValue);
%>
<%
response.addCookie(cookie);
out.println("My cookie has been set to"+ MyCookieName +"="+MyCookieValue);
%>
</body>
</html>
Example2: How to read a cookie
<html>
<head>
<title> JSP Programming </title>
</head>
<body>
<%! String MyCookieName="UserID";
String MyCookieValue, CName,CValue;
int found=0, i=0;
%>
<%
Cookie[] cookies=request.getCookies();
for(i=0;i < cookies.length;i++)
{
CName=cookies[i].getName();
CValue=cookies[i].getValue();
if(MyCookieName.equals(CName))
{
found=1;
MyCookieValue=CValue;
}
}
if(found==1){ %>
<p> Cookie name =<%= MyCookieName %> </p>
<p> Cookie value =<%= MyCookieValue %> </p>
<% } %>
</body>
</html>
46
Java and J2EE
JSP Sessions
In any web application, the user moves from one page to another and it becomes necessary to
track the user data through out the application. JSP provides an implicit object session which can
be used to save the data specific to that particular user.
Example1: How to create a session attribute
<html>
<head>
<title> JSP Programming </title>
</head>
<body>
<%! String AtName = “Product”;
String AtValue=“1234”;
session.setAttribute(AtName, AtValue);
</body>
</html>
Example2: How to read session attribute
<html>
<head>
<title> JSP Programming </title>
</head>
<body>
<%!
Enumeration e = request.getAttributesNames();
47
Java and J2EE
while(e.hasMoreElements())
{
String AtName = (String)e.nextElement();
String AtValue = (String)sesion.getAttribute(AtName); %>
<p>Attribute Name <%= AtName %></p>
<p>Attribute Value <%= AtValue %> </p>
<% } %>
</body>
</html>
Review Questions
Q. What is JSP? How JSP differs from Java Servlets (5M)
Q. How Does JSP work?
or
Q. Explain the JSP architecture?
Q. What are the advantages of JSP?
Q. Explain the life cycle methods of JSP?
Q. List and Explain the different types of JSP tags (5M)
Q. Explain the method of deployment of JSP with the Tomcat
Q. Develop a JSP page that displays the current date and time
Q. How can I declare variables and objects within my JSP page? Explain with example
Q. How can I declare methods within my JSP page? Explain with example
Q. How to use control statements in jsp code
Q. How to use loops in JSP code
Q. Explain how JSP handles request string posted from an HTML file
or
Q. Explain how JSP handles HTTP Get and Post request with example
or
Q. Write a JSP program which displays the first name and last name entered by the user from an
HTML file
Q. What are implicit objects? List them
Q. What are cookies? How to set and display cookie in JSP?
Q. Explain with example how to maintain sessions in JSP (5M)
48

More Related Content

What's hot

Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postvamsi krishna
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsJavaEE Trainers
 
Java servlets
Java servletsJava servlets
Java servletslopjuan
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtapVikas Jagtap
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programmingKumar
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersFernando Gil
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technologyTanmoy Barman
 

What's hot (20)

Servletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,postServletarchitecture,lifecycle,get,post
Servletarchitecture,lifecycle,get,post
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
JAVA Servlets
JAVA ServletsJAVA Servlets
JAVA Servlets
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Java servlets
Java servletsJava servlets
Java servlets
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Servlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servletsServlet/JSP course chapter 1: Introduction to servlets
Servlet/JSP course chapter 1: Introduction to servlets
 
Java servlets
Java servletsJava servlets
Java servlets
 
Jsp servlets
Jsp servletsJsp servlets
Jsp servlets
 
Servlet ppt by vikas jagtap
Servlet ppt by vikas jagtapServlet ppt by vikas jagtap
Servlet ppt by vikas jagtap
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
Servlets
ServletsServlets
Servlets
 
java servlet and servlet programming
java servlet and servlet programmingjava servlet and servlet programming
java servlet and servlet programming
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Servlets
ServletsServlets
Servlets
 
Java EE 01-Servlets and Containers
Java EE 01-Servlets and ContainersJava EE 01-Servlets and Containers
Java EE 01-Servlets and Containers
 
Servlets
ServletsServlets
Servlets
 
Servlet
Servlet Servlet
Servlet
 
java Servlet technology
java Servlet technologyjava Servlet technology
java Servlet technology
 

Viewers also liked (20)

JSP
JSPJSP
JSP
 
remote method invocation
remote method invocationremote method invocation
remote method invocation
 
Jdbc 1
Jdbc 1Jdbc 1
Jdbc 1
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
Java annotation
Java annotationJava annotation
Java annotation
 
Ravi Tuppad
Ravi TuppadRavi Tuppad
Ravi Tuppad
 
Java rmi
Java rmiJava rmi
Java rmi
 
Rmi architecture
Rmi architectureRmi architecture
Rmi architecture
 
Introduction in jsp & servlet
Introduction in jsp & servlet Introduction in jsp & servlet
Introduction in jsp & servlet
 
Java Annotations
Java AnnotationsJava Annotations
Java Annotations
 
PHP - Introduction to Object Oriented Programming with PHP
PHP -  Introduction to  Object Oriented Programming with PHPPHP -  Introduction to  Object Oriented Programming with PHP
PHP - Introduction to Object Oriented Programming with PHP
 
Basic java
Basic java Basic java
Basic java
 
Introduction To Rmi
Introduction To RmiIntroduction To Rmi
Introduction To Rmi
 
Rmi
RmiRmi
Rmi
 
Java RMI
Java RMIJava RMI
Java RMI
 
Networking
NetworkingNetworking
Networking
 
Rmi ppt-2003
Rmi ppt-2003Rmi ppt-2003
Rmi ppt-2003
 
Java Annotation
Java AnnotationJava Annotation
Java Annotation
 
Java networking programs - theory
Java networking programs - theoryJava networking programs - theory
Java networking programs - theory
 

Similar to Java Servlets & JSP

Similar to Java Servlets & JSP (20)

AJppt.pptx
AJppt.pptxAJppt.pptx
AJppt.pptx
 
Jsp and Servlets
Jsp and ServletsJsp and Servlets
Jsp and Servlets
 
Web container and Apache Tomcat
Web container and Apache TomcatWeb container and Apache Tomcat
Web container and Apache Tomcat
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3 server side technology
Wt unit 3 server side technologyWt unit 3 server side technology
Wt unit 3 server side technology
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Unit5 servlets
Unit5 servletsUnit5 servlets
Unit5 servlets
 
Jdbc
JdbcJdbc
Jdbc
 
Jsp and jstl
Jsp and jstlJsp and jstl
Jsp and jstl
 
Servlet and jsp development with eclipse wtp
Servlet and jsp development with eclipse wtpServlet and jsp development with eclipse wtp
Servlet and jsp development with eclipse wtp
 
Java Servlet
Java ServletJava Servlet
Java Servlet
 
J2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - ComponentsJ2EE - JSP-Servlet- Container - Components
J2EE - JSP-Servlet- Container - Components
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Cis 274 intro
Cis 274   introCis 274   intro
Cis 274 intro
 
Html servlet example
Html   servlet exampleHtml   servlet example
Html servlet example
 
Servlet 01
Servlet 01Servlet 01
Servlet 01
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Http Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responsesHttp Server Programming in JAVA - Handling http requests and responses
Http Server Programming in JAVA - Handling http requests and responses
 
Tomcat Configuration (1)
Tomcat Configuration (1)Tomcat Configuration (1)
Tomcat Configuration (1)
 

Java Servlets & JSP

  • 1. Java and J2EE Java Servlets What is a Java Servlet? A java servlet is a server side program that is called by the user interface or another J2EE component and contains the business logic to process a request What is Common Gateway Interface(CGI)? Originally, a server-side program handled client requests by using the Common Gateway Interface (CGI), which was programmed using Perl. It is the standard for creating dynamic web pages. It is a part of the web server that can communicate with other programs running on the server. How CGI woks? Figure. How CGI works 1. Client sends a request to server 2. Server starts a CGI script 3. Script computes a result for server and quits 4. Server returns response to client 5. Another client sends a request 6. Server starts the CGI script again etc. What are the disadvatages/drawback of CGI? • Each time a CGI script is called, a separate process is created • It was also expensive to open and close database connections for each client request • CGI programs were not platform independent • Once CGI program terminates, all data used by the process is lost and can not be used by the other CGI programs • Only defines interface, no supporting infrastructure (security, sessions, persistence, etc.) 1 1 23 4 5 1 23 4 5
  • 2. Java and J2EE How Servlet works? Figure. How Servlet works 1. Client sends a request to server 2. Server starts a servlet 3. Servlet computes a result for server and does not quit 4. Server returns response to client 5. Another client sends a request 6. Server calls the servlet again etc. What are the advantages of Servlets over CGI? • Performance is significantly better 2 1 23 4 5
  • 3. Java and J2EE • persistence. This means that java servlet remains alive after the request is fulfilled. A servlet stays in memory, so it doesn’t have to be reloaded each time • Portable - will run on any J2EE-compliant server • Platform Independence Servlets are written entirely in java so these are platform independent. • Secure • Full functionality of java class libraries is available to servlet Explain the Life Cycle of a Servlet? The javax.servlet.Servlet interface defines the three methods known as life-cycle method. These are: init(), service(), destroy() – defined in javax.servlet.Servlet interface The init() method When a servlet is first loaded, the init() method is invoked. This allows the servlet to perform any setup processing such as opening files or establishing connections to their servers. If a servlet is permanently installed in server, it loads when the server strts to run, otherwise, the server activates a servlet when it receives the first client request. Note that init() will only be called only once; it will not be called again unless the servlet has been unloaded and then reloaded by the server. 3
  • 4. Java and J2EE Figure. Servlet Life cycle What you need to run servlets? o JDK 1.2 or higher. o A servlet-compatible webserver. (E.g. Tomcat ) Using Tomcat for Servlet Development To create servlets, you will need access to a servlet development environment. One such used is Tomcat. Tomcat is the Servlet Engine that handles servlet requests. Tomcat is open source (and therefore free). It contains the class libraries, documentation and runtime support that you will need to create and test servlets. You can download tomcat from jakarta.apache.org. Installing the Tomcat server The Java software Development Kit(JDK) should be installed on your computer before installing tomcat. Then install Tomcat server. The default location for Tomcat5.5 is C:Program FilesApache Software FoundationTomcat 5.5 To Start Tomcat Tomcat must be running before you try to execute a servlet. Select start | Programs Menu | Apache Tomcat 5.5 | Monitor Tomcat, then a tomcat icon appears on the right bottom tray of the task bar. Right click on the icon and choose start service. Test Tomcat You can test whether the tomcat is runing or not by requesting on a web browser http://localhost:8080 4
  • 5. Java and J2EE Figure: Tomcat start page Set two environment variables: Tomcat uses an environmental variable JAVA_HOME to indicate the location of the JDK top- level directory. You may need to set the environmental variable JAVA_HOME to the top-level directory in which the Java Development Kit is installed( say C:JDK1.5). The directory C:Program FilesApache Software FoundationTomcat 5.5commonlib contains servlet-api.jar. This jar file contains the classes and interfaces that are needed to buils servlet. To make this file accessible, update your CLASSPATH envirinment variable so that it includes C:Program FilesApache Software FoundationTomcat 5.5commonlibservlet-api.jar Placing the compiled servlet class file in the proper Tomcat directory: Once you have compiled a servlet, you must enable the tomcat to find it. Copy the servlet class file into the following directory: C:Program FilesApache Software FoundationTomcat 5.5webappsservlets-examplesWEB- INFclasses Add Servlet Name & mapping to the web.xml : Add the servlet’s name and mapping to the web.xml file located in the follwing directory. C:Program FilesApache Software FoundationTomcat 5.5webappsservlets-examplesWEB- INF For example assuming the first example, called HelloWorld, you will add the following lines in the section that defines the servlet. <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> 5
  • 6. Java and J2EE </servlet> Next, add the following lines to the section that defines the servlet mappings <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/servlet/HelloWorld</url-pattern> </servlet-mapping> Follow the same general procedure for all the examples. Steps involved in building and testing a servlet 1. Create and compile the servlet source code. Then copy the servlet’s class file to the proper directory, and add the servlet’s name and mappings to the proper web.xml file 2. Start Tomcat 3. Start a Web browser and request the servlet. Your First Servlet - HelloWorld Now let's write a simple java servlet that writes "Hello World!" to the browser: import javax.servlet.*; import java.io.*; public class HelloWorld extends GenericServlet { public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException { // Set the content type of the response. resp.setContentType ("text/html"); // Get an output stream object from the response PrintWriter out = resp.getWriter (); // Write body content to output stream // The first part of the response. out.println ("<html>"); out.println ("<head><title> Test </title></head>"); out.println ("<body>"); // The greeting. out.println ("Hello World!"); // Last part. out.println ("</body>"); 6
  • 7. Java and J2EE out.println ("</html>"); } } Explaination: Here this file should be named as HelloWorld.java. It is extending GenericServlet. So the related packages are imported. service() is the method by which we manipulate the client’s request and responses. It has two arguments. First, req is an object that is implementing the ServletRequest interface and secondly, resp is an object that is implementing the ServletResponse interface. These are used to handle the request and responses. Other methods that are usually called to handle data are doPost, doPut, doTrace, doHead, etc. It is throwing two exceptions: IOException and ServletException. IOException usually arises when the servlet is loaded to the web and ServletException can occur anytime. So it has to be handled. resp.setContentType("text/html"); This statement sets the MIME header using the method setContentType() in the response. PrintWriter out=resp.getWriter(); Here we are getting hold of a handle to write into the output stream. You get a handle by using the method getWriter() which is implemented by the java.io.PrintWriter class. We write HTML to the output, e.g., out.println ("<html>"); out.println ("<head><title> Test </title></head>"); write the greeting out.println("Hello World "); Compiling a Servlet → Run javac HelloWorld.java from the command line. HelloWorld.java compiles to HelloWorld.class. → Class file should be located in the web application’s classes folder: C:<tomcat home>webappsservlets-examplesWEB-INFclasses Adding Servlet Name & mapping to the web.xml  Consider a Servlet residing in folder 7
  • 8. Java and J2EE webappsservlets-examplesWEB-INFclassesHelloWorld.class  Assign a name to the servlet in web.xml <servlet> <servlet-name>HelloWorld</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet>  Map a servlet to a custom URL <servlet-mapping> <servlet-name>HelloWorld</servlet-name> <url-pattern>/servlet/HelloWorld</url-pattern> </servlet-mapping>  Start the Tomcat Tomcat must be running before you try to execute a servlet.  Run the Servlet using the following URL: http://localhost:8080/servlets-examples/servlet/HelloWorld  Tomcat internally maps all URLs starting with /servlet/* to the /WEB-INF/classes folder. What is web.xml The web.xml file specifies various config. parameter such as: • the name used to invoke the servlet • description of the servlet • the class name of the servlet class Sample file entry 8
  • 9. Java and J2EE What is Servlet API Two packages contain the classes and interfaces that are required to build servlets. These are: • javax.servlet • javax.servlet.http They constitute the Servlet API. These packages are not part of the java core packages. Instead, they are standard extensions provided by Tomcat. javax.servlet Package The javax.servlet package contains a number of classes and interfaces that establish the framework in which servlet operate. It contains the classes necessary for a standard, protocol- independent servlet. The following table summarizes the core interfaces that are provided in this package. Interfaces 9
  • 10. Java and J2EE Interface Description Servlet Defines methods that all servlets must implement. ServletConfig A servlet configuration object used by a servlet container used to pass information to a servlet during initialization. ServletContext Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file. ServletRequest Defines an object to provide client request information to a servlet. ServletRespons e Defines an object to assist a servlet in sending a response to the client. The Servlet interface All servlets must implement the Servlet interface. It declares the init(), service(), and destroy() methods that are called by the server during the life cycle of a servlet. The methods defined by Servlet are shown below. Methods 10
  • 11. Java and J2EE The ServletConfig interface The ServletConfig interface allows a servlet to obtain configuration data when it is loaded. The methods declared by this interface are summarized below. Methods The ServletContext Interface The ServletContext interface enables servlets to obtain information about their environment. Several of its methods are summarized below. 11
  • 12. Java and J2EE Methods The ServletRequest Interface The ServletRequest interface enables a servlet to get information about a client request. Several of its methods are summarized below. Methods: The ServletResponse Interface 12
  • 13. Java and J2EE - The ServletResponse interface enables a servlet to formulate a response for a client. Several of its methods are summarized below. Methods Classes The following table summarizes the core classes that are provided in javax.servlet package. Class Description GenericServlet Defines a generic, protocol-independent servlet. ServletInputStream Provides an input stream for reading binary data from a client request, including an efficient readLine method for reading data one line at a time. ServletOutputStream Provides an output stream for sending binary data to the client. ServletException Defines a general exception a servlet can throw when it encounters difficulty. UnavailableException Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily unavailable The GenericServlet class The GenericServlet class provides the framework for developing basic servlets. If you are creating a protocol-independent servlet, you probably want to subclass this class rather than implement the Servlet interface directly. Note that the service() method is declared as abstract; this is the only method you have to override to implement a generic servlet. GenericServlet includes basic implementations of the init() and destroy() methods, 13
  • 14. Java and J2EE Reading servlet parameters The ServletRequest interface includes methods that allow you to read the names and values of parameters that are included in a client request. We will develop s servlet that illustrate their use. Example: Shows all the parameters sent to the servlet via POST request The example contains two files: • PostParameters.html : An HTML form that sends a number of parameters to the servlet via post request • ShowPostParameters.java: A servlet that read the names & values of parameters sent that are included in post request PostParameters.html: It defines a table that contains two labels and two text fields. One of the label is Employee and the other is Phone. There is also a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies the servlet to process the HTTP POST request. <HTML> <HEAD> <TITLE>A Show Parameters using POST</TITLE> </HEAD> <BODY BGCOLOR="#FDF5E6"> <FORM ACTION="http://localhost/servlets-examples/servlet/ShowPostParameters" METHOD="POST"> <table> <tr> <td><b> Employee </td> <td><INPUT TYPE="TEXT" NAME="e"></td> </tr> <tr> <td><b> Phone </td> <td><INPUT TYPE="TEXT" NAME="p"></td> </tr> </table> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML> Note: Copy the PostParameters.html file under C:<Tomcat-Install-Directory>webappsROOT ShowPostParameters.java : import java.io.*; import javax.servlet.*; import java.util.*; public class ShowPostParameters extends GenericServlet 14
  • 15. Java and J2EE { public void service(ServletRequest req,ServletResponse resp) throws ServletException, IOException { // Set the content type of the response. resp.setContentType("text/html"); // Extract the PrintWriter to write the response. PrintWriter out = resp.getWriter(); // The first part of the response. out.println ("<html>"); out.println ("<head><title> Test </title></head>"); out.println ("<body>"); // Now get the parameters and output them back. out.println ("Request parameters: "); Enumeration e = req.getParameterNames(); while(e.hasMoreElements()) { String pname = (String)e.nextElement(); String pvalue = req.getParameter(pname); out.print(pname + "=" + pvalue); } // Last part. out.println("</body>"); out.println("</html>"); out.close(); } } Explaination • We need to import java.util.Enumeration. • The service() method is overridden to process client requests • Whatever parameters were provided are all in the ServletRequest instance. • We can list these parameters by getting an Enumeration instance from the request by calling getParameterNames(): Enumeration e = req.getParameterNames(); • The "name" of a parameter is really the string in the name attribute of the tag for the particular Form element. 15
  • 16. Java and J2EE • For example, the name string is ‘e’ below. Employee: <input type="text" name="e"> • Now, if we want to retrieve the actual string typed in by the user, we use that name in getParameter(): String whatTheUserTyped = req.getParameter ("e"); javax.servlet.http Package • Contains number of classes and interfaces that are commonly used by servlet developers • Its functionality makes it easy to build servlets that work with HTTP requests and response . i.e. The javax.servlet.http package supports the development of servlets that use the HTTP protocol The following table summarizes the core inerfaces that are provided in this package. Interfaces: Interface Description HttpServletRequest Extends the ServletRequest interface that enables the servlets to read data from an HTTP request. HttpServletResponse Extends the ServletResponse interface that enables servlets to write data to an HTTP response. HttpSession 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 HttpServletRequest Interface The HttpServletRequest interface enables a servlet to obtain information about a client request. Several of its methods are shown below. Methods: 16
  • 17. Java and J2EE Cookie[] getCookies() - Gets the array of cookies found in this request. String getMethod() - Gets the HTTP method (for example, GET, POST, PUT) with which this request was made. String getQueryString() - Gets any query string that is part of the HTTP request URI. HttpSession getSession(boolean create) - Gets the current valid session associated with this request, if create is false or, if necessary, creates a new session for the request, if create is true. The HttpServletResponse Interface The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client. Several of its methods are shown below. Methods: void addCookie(Cookie cookie) - Adds the specified cookie to the response. The HttpSession Interface • 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. • A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs. Several of its methods are shown below. Methods long getCreationTime() - Returns the time at which this session representation was created, in milliseconds String getId() - Returns the identifier assigned to this session. long getLastAccessedTime() - Returns the last time the client sent a request carrying the identifier assigned to the session. 17
  • 18. Java and J2EE Object getAttribute(String name) - Returns the object bound with the specified name in this session, or null if no object is bound under the name. void setAttribute(Sring name, Object value) - Binds an object to this session, using the name specified. Classes The following table summarizes the core classes that are provided in this package. The HttpServlet class • The HttpServlet class extends GenericServlet • It is commonly used when developing servlets that receive and process HTTP requests Methods void doGet(HttpServletRequest req, HttpServletResponse resp) - Handles an HTTP GET request void doPost(HttpServletRequest req, HttpServletResponse resp) - Handles an HTTP POST request Handling HTTP Requests and Responses • HttpServlet class provides various methods that handle the various types of HTTP requests • A servlet developer typically overrides one of these methods • These methods are doGet(), doPost() etc Handling HTTP GET requests Here we will develop a servlet that handles an HTTP GET request. The servlet is invoked when a form on a web page is submitted. The example contains two files. • ColorGet.html • ColorGetservlet.java ColorGet.html: It defines a form that contains a select element and a submit button. Notice that the action attribute of the form tag specifies a URL. The URL identifies a servlet to process the HTTP request. <HTML> <HEAD> <TITLE>Handling HTTP GET request</TITLE> </HEAD> 18 Class Description Cookie Creates a cookie, a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. HttpServlet Provides methods to handle HTTP requests & responses.
  • 19. Java and J2EE <BODY BGCOLOR="#FDF5E6"> <FORM ACTION="http://localhost:8080/servlets-examples/servlet/ColorGetServlet" METHOD=“GET"> <B>Color: <select name=“color” > <option value=“Red” >Red </option> <option value=“Green” >Green </option> <option value=“Blue” >Blue </option> </select><BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML> ColorGetServlet.java : In this file doGet() method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter() method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated. import java.io.*; import javax.servlet.*; import javax.servlet.htto.*; public class ColorGetServlet extends HttpServlet { public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { // set MIME type resp.setContentType("text/html"); //Get print writer PrintWriter out = resp.getWriter(); // Get the value of slection that was made by user String color = req.getParameter("color"); out.println("The selected color is=" + color); out.close(); } } Handling HTTP POST requests Same as that of handling HTTP GET request, Note the following changes: • Replace method=”get” in HTML form to method=”post” • In servlet, override doPost(), instead of doGet() • What is the difference between HttpServlet and GenericServlet? 19
  • 20. Java and J2EE GenericServlet is a generalised and protocol independent servlet which defined in javax.servlet package. Servlets extending GenericServlet should override service() method. javax.servlet.http.HTTPServlet extends GenericServlet. HTTPServlet is http protocol specific ie it services only those requests thats coming through http.A subclass of HttpServlet must override at least one method of doGet(), doPost(). What is the difference between the doGet and doPost methods? doGet() is called in response to an HTTP GET request. This happens with some HTML FORMs (those with METHOD=”GET” specified in the FORM tag). doPost() is called in response to an HTTP POST request. This happens with some HTML FORMs (those with METHOD="POST" specified in the FORM tag). Both methods are called by the default implementation of service() in the HttpServlet base class. Cookie class What is a cookie? Cookies are short pieces of data sent by a web servers to the client browser. The cookies are saved to the hard disk of the client in the form of small text file. Cookies help the web servers to identify web users and tracking them in the process. A cookie consists of one or more name- value pairs containing bits of information such as user preferences, shopping cart contents, the identifier for a server-based session, or other data used by websites. In servlet, cookies are object of the class javax.servlet.http.Cookie. this class is used to create cookie, a small amount of information sent by the servlet to a web browser, saved by web browser and later sent back to the server. The value of cookie can uniquely identify a client, so cookies are commonly used for session tracking. A cookie is composed of two pieces. These are cookie name and cookie value. The cookie name is used to identify a particular cookie from among other cookies stored at client. The cookie value is data associated with the cookie. Cookies van be constructed using the following code. Cookie(String CookieName, String CookieValue) The first argument is the String object that contains the name of the cookie. The other argument is a String object that contains the value of the cookie E.g Cookie cookie = new Cookie("ID", "123"); In this example, a cookie called ‘ID’ is being created and assigned the value 123. 20
  • 21. Java and J2EE A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of HttpServletResponse void addCookie(Cookie cookie) A servlet can read a cookie by calling the getCookies() method of the HttpServletRequest object. It returns an array of cookie objects. Cookie objects have the following methods Methods int getMaxAge() - Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown. String getName() - Returns the name of the cookie. String getValue() - Returns the value of the cookie. int getVersion() - Returns the version of the protocol this cookie complies with. void setMaxAge(int expiry) - Sets the maximum age of the cookie in seconds. void setValue(String newValue) - Assigns a new value to a cookie after the cookie is created. Using Cookies Let us develop a servlet that illustrates how to use cookies. Example: Program to create and display cookie The program contains three files as summarized below: AddCookie.html : Allows a user to specify a name & value for the cookie AddCookieServlet.java : Processes the submission of AddCookie.html GetCookieServlet.java : Displays cookie name & values. AddCookie.html <html><body><center> <form method="post" action="http://localhost:8080/servlets-examples/servlet/AddCookieServlet"> <B> Enter the Name for Cookie:</B> <input type=text name="name" ><br><br> Enter the value for a Cookie: <input type=text name="data" > <input type=submit value="submit"> </form></body></html> AddCookieServlet.java import java.io.*; 21
  • 22. Java and J2EE import javax.servlet.*; import javax.servlet.http.*; public class AddCookieServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Get paramater from HTTP request String name=req.getParameter(“name”); String data=req.getParameter(“data”); // Create cookie Cookie cookie=new Cookie(name ,data); // Add cookie to HTTP response resp.addCookie(cookie); // write output to browser resp.setContentType(“text/html”); PrintWriter pw= resp.getWriter(); pw.println(“<B>MyCookie has been set to “); pw.println( “<b>” + name + “ = ” + data); pw.close(); }} GetCookieServlet.java import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class GetCookieServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // Get cookies from header of HTTP request Cookie[] cookies=req.getCookies(); //Display these cookies resp.setContentType("text/html"); PrintWriter pw=resp.getWriter(); pw.println("<b>"); for (int i=0;i<cookies.length;i++) { String name=cookies[i].getName(); String value=cookies[i].getValue(); pw.println("Name="+name + "Value= " + value +"<br><br>"); } pw.close(); } } 22
  • 23. Java and J2EE Disadvantages of cookies 1. Cookies exist as plain text on the client machine and they may pose a possible security risk as anyone can open and tamper with cookies. 2. Users can delete a cookies. 3. Users browser can refuse cookies,so your code has to anticipate that possibility. Session Tracking Cookies are stored on client side where as sessions are server variables.Sessions grew up from cookies as a way of storing data on the server side, because the inherent problem of storing anything sensitive on clients' machines is that they are able to tamper with it if they wish. What is session? HTTP is a stateless protocol, each request is independent of the previous one. However in some applications, it is necessary to save state information so that information can be collected from several interactions between a browser and a server. Sessions provide such a mechanism. The session is an object used by a servlet to track a user's interaction with a Web application across multiple HTTP requests. The session is stored on the server. A java servlet is capable of tracking sessions by using HttpSession interface. An object that implements this interface can hold information for one user session between requests. A session can be created via getSession() method of HttpServletRequest. An HttpSession object is returned E.g. HttpSession session = req.getSession(true); This method takes a boolean argument. true means a new session shall be started if none exist, while false only returns an existing session. The HttpSession object is unique for one user session. You can add data to an HttpSession object with the setAttribute() method. The method requires two arguments. The first argument is the String object that contains the name of the attribute. The other argument is an object binded with value void setAttribute(Sring name, Object value) This method binds the binds the specified object value under the specified name. To retrirve an object from session use getAttribute(). This method requires one argument that contains the name of the attribute whose value you want to retrive. Object getAttribute(String name) This method returns the object bound under the specifed name You can also get the names of all of the objects bound to a session with getAttributeNames() Enumeration getAttributeNames() 23
  • 24. Java and J2EE This returns an Enumeration containing the names of all objects bound to this session as String objects or an empty Enumeration if there are no bindings. The following servlet illustrate how to use session state. Example: Program to create a session and display session information such as current date and time and the date and time the page was last accessed. import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class DateServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); //Get the HTTP Session object HttpSession hs = req.getSession(true); // Display the date/time of last access Date date = (Date)hs.getAttribute(“date”); if(date != null) { out.println(“Last access: " + date + "<br>"); } // Display current date/time: date = new Date(); hs.setAttribute(“date”,date); out.println(“Current date :" + date); } } Explaination: The getSession() method gets the current session. A new session is created if one does not already exist. The getAttribute() method is called to obtain the object that is bound to the name “date”. That object is a Date object that encapsulates the date and time when this page was last accessed.( ofcourse there is no such binding when the page is first accessed). A Date object encapsulating the current date and time is created. The setAttribute() method is called to bind the name “date” to this object. Output: When the web page is accessed first time. A session is created. What is the difference between session and cookie? 24
  • 25. Java and J2EE 1) Sessions are stored in the server side whereas cookies are stored in the client side 2) Session should work regardless of the settings on the client browser. even if users decide to forbid the cookie (through browser settings) session still works. There is no way to disable sessions from the client browser. 3) Session and cookies differ in type and amount of information they are capable of storing. javax.servlet.http.Cookie class has a setValue() method that accepts Strings. javax.servlet.http.HttpSession has a setAttribute() method which takes a String to denote the name and java.lang.Object which means that HttpSession is capable of storing any java object. Cookie can only store String objects. What are GET and POST? o When Form data is sent by the browser, it can be sent in one of two ways: (1) using the GET method and (2) using the POST method. o In the GET method, the form data (parameters) is appended to the URL, as in: http://localhost:8080/servlets-examples/servlet/ColorGetServlet?name=girish Here, the text field contains girish. o In the POST method, the browser simply sends the form data directly. o When you create an HTML form, you decide whether you want to use GET or POST. o When you use GET, the doGet() method of your servlet is called, otherwise the doPost() method is called. o The standard practice is to use POST, unless you need to use GET. Exercises Exercise1 Develop a servlet to accept user name from an HTML form and display a greeting message. HTML File <html> <body bgcolor=blue> <form action="http://localhost:8080/servlets-examples/servlet/GreetingServlet " method="post"> <center><h3><font color=”red”>Enter Your Name</font> </h3> <input type="text" name="name"> <br><br> 25
  • 26. Java and J2EE <input type="submit" value="Submit"> <input type="reset" value="Reset"> </center> </form> </body> </html> Servlet file import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class GreetingServlet extends HttpServlet { public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); String name = req.getParameter(“name”); out.println(“<html><title>Greeting Message</title></head>”); out.println(“<body bgcolor=wheat><h2>”); out.println(“ Hello ”+name+”, How are you?”); out.println(“</h2></body></html>”); out.close(); } } Exercise2 Develop a simple web application on a Tomcat server that includes an HTML page that takes user name from the clients and submits the request to a java servlet. The servlet validates the request: a) If the input is empty, it displays a page to report an error b) If the input is valid, it displays greeting message to the user 26
  • 27. Java and J2EE HTML File <html> <body > <form action="http://localhost:8080/servlets-examples/servlet/GreetingServlet " method="post"> <center><h3><font color=”red”>Enter Your Name</font> </h3> <input type="text" name="name"> <br><br> <input type="submit" value="Submit"> <input type="reset" value="Reset"> </center> </form> </body></html> Servlet file import javax.servlet.*; import javax.servlet.http.*; import java.io.*; public class GreetingServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { resp.setContentType("text/html"); PrintWriter out=resp.getWriter(); out.println("<html><title>Greeting Message</title></head>"); out.println("<body bgcolor=wheat><h2>"); // read the name parameter value String name = req.getParameter("name"); // request.getParameter() returns the value of "" (empty string) if the text field was blank // and trim() method is used to remove the blank spaces from both ends of the empty string if(name.trim().equals("")) { out.println(" Error: Missing name "); 27
  • 28. Java and J2EE } else { out.println(" Hello " +name+", How are you?"); } out.println("</h2></body></html>"); out.close(); } } Review Questions Q. What is java servlet? What are the advatages of servlet over traditional CGI? Q. Compare servlet with traditional CGI Q. How servlet works? Q. Explain the life cycle methods of a servlet. Q. Explain how to setup tomcat for servlet development Q. What are the general steps involved in building and testing a servlet Q. What are the classes and interfaces contained in the javax.servlet package? Q. Explain the following interfaces and their methods provided in the javax.servlet package i) Servlet ii) ServletConfig iii) ServletContext iv) ServletRequest v) ServletResponse Q. Explain with example how to read parameters in a servlet? or Write a servlet program to accept Employee name and phone from an HTML form and display them in a web page by passing parameters. or How does a servlet read data entered in an HTML form? or Write a simple application in which the HTML form can invoke a servlet 28
  • 29. Java and J2EE Q. What are the classes and interfaces contained in the javax.servlet.http package? Q. Explain the following interfaces and their methods provided in the javax.servlet.http package i) HttpServletRequest ii) HttpServletResponse iii) HttpSession Q. Write a servlet program that handles HTTP GET request containing data that is supplied by the user as a part of the request. Q. Explain how servlet deals HTTP Get and Post requests with an example Q. What are cookies? How java servlet support cookies? Explain with example Q. Develop a java servlet to create and display cookie Q. Write a servlet that will send a cookie containing your name to the client. Then invoke the servlet, find and view the cookie file and note its contents. Q. What is the use of session tracking? How java servlet support the session tracking? explain with example Q. What is the difference between session and cookie? Q. Write a servlet that will read the name value from the following form. If the name is non- blank, the servlet should bind it to the session and replay with “Hello <name>”. If the name is blank, the servlet should look for a name previously bound to the session and replay with that instead (if it exists). <form method=”post” action=”/hello”> Name: <input type="text" name="name"> <input type="submit" value="Submit"> </form> Servlet file: hello.java import java.io.*; import java.util.*; import javax.servlet.*; import javax.servlet.http.*; public class hello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { 29
  • 30. Java and J2EE resp.setContentType("text/html"); PrintWriter out = resp.getWriter(); //Get the HTTP Session object HttpSession hs = req.getSession(true); // Get the value of the name entered in text field String name=req.getParameter("name"); // Get the object bound with the specified name in this session, if it exists String sname = (String)hs.getAttribute("name"); // if name is non blank bind it to the session otherwise display the object bound to the // specified name if(sname == null) { hs.setAttribute("name",name); out.println(" Hello " + name ); } else { out.println("Hello :" + sname); } } } Q. Write a servlet that will process the HTTP request coming from the following form. The servlet should obtain the values of the two fields. Then display their sum, if both are numeric or zero otherwise. <form method=”post” action=”/summation”> A: <input type="text" name="value1"><br> B: <input type="text" name="value2"> <input type="submit" value="Add"> </form> Servlet file: summation.java import java.io.*; 30
  • 31. Java and J2EE import javax.servlet.*; import javax.servlet.http.*; import java.util.*; public class summation extends HttpServlet { public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { // set MIME type resp.setContentType("text/html"); //Get print writer PrintWriter out = resp.getWriter(); // read the values of parameters String v1 = req.getParameter("value1"); String v2 = req.getParameter("value2"); // convert the parameter values in to integer fromat int value1=Integer.parseInt(v1); int value2=Integer.parseInt(v2); int sum=0; // verify whether the values of the fields are numeric, if yes add the values and print sum // otherwise output sum as zero if(value1 > 0 && value2 >0) { sum=value1+value2; out.println("Sum =" + sum); } else { out.println("sum=0"); } } 31
  • 32. Java and J2EE } Q. Write a Servlet program that takes your name and address from an HTML form and displays it Java Server Pages(JSP) What is JSP? - Java Server Page(JSP) is a server side program that is similar in design & functionality to a java servlet - JavaServer Pages is the Java 2 Platform, Enterprise Edition(J2EE) technology for building applications for generating dynamic web content How JSP differs from Java servlet? or Compare JSP with Java servlet • A Java Servlet is written using the Java Programming Language and responses are encoded as an output String object that is passed to the println() method. The output String object is formatted in HTML,XML or whatever formats are required by the client. i.e. In Servlets you need to have lots of println statements to generate HTML. E.g. out.println("<HTML><BODY>"); out.println("<H2>Welcome to my servlet page.</H2>"); out.println("</BODY></HTML>"); 32
  • 33. Java and J2EE • In contrast, JSP is written in HTML,XML or in the client’s format that is interpersed with scripting elements, directives and actions comprised of Java Programming language and JSP syntax i.e. JSPs are essentially an HTML page with special JSP tags embedded. These JSP tags can contain Java code. E.g. • Servlet is written in java lang, • Whereas jsp contains both jsp tags and html tags. JSP offers basically the same features found in java servlet because a JSP is converted to a Java servlet the first time that a client requests the JSP. • Servlet is a java class, So for every change, we have to compile the code to reflect the change.Mainly using for writing business logics (i.e. functional design) • JSP is a file, It’s automatically converted into a servlet on deploying. We can't compile it explicitly, the changes will get reflect by saving the file. Its mainly used for presentation of data (i.e. web page design(look and feel)) How Does JSP work? Or 33
  • 34. Java and J2EE Explain the JSP architecture? 1. The user goes to a web site made using JSP. The user goes to a JSP page (ending with .jsp). The web browser makes the request via the Internet. 2. The JSP request gets sent to the Web server. 3. The Web server recognises that the file required is special (.jsp),therefore passes the JSP file to the JSP Servlet Engine. 4. If the JSP file has been called the first time,the JSP file is parsed,otherwise go to step 7. 5. The next step is to generate a special Servlet from the JSP file. All the HTML required is converted to println statements. 6. The Servlet source code is compiled into a class. 7. The Servlet is instantiated,calling the init and service methods. 8. HTML from the Servlet output is sent via the Internet. 9. HTML results are displayed on the user's web browser. What are the advantages of JSP? 34
  • 35. Java and J2EE • Content and display logic are separated • Recompile automatically when changes are made to the source file • Platform-independent Explain the Life Cycle methods of JSP? Overall, the request-response mechanism and the JSP life cycle are the same as those of a servlet. There are three methods that are automatically called when a JSP is requested & when the JSP terminates normally. These are: • jspInit() • service() • jspDestroy() • The jspInit() method is identical to init() method in a java servlet and executed first after the JSP is loaded. It is used to initialize objects and variables that are used throughout the life of the JSP. • service() is the JSP equivalent of the service() method of a servlet class. The server calls the service() for each request, passing it the request and the response objects • The jspDestroy() method is identical to the destroy() method in a java servlet. It is automatically called when the JSP terminates. It is used for clean up where resources used during the execution of the JSP are released, such as disconnecting from a database. What you need to build and test Java Server Page? • JDK 1.2 or higher. • JSP enabled server installed. E.g Tomcat JSP Container Explain the method of deployment of JSP with the Tomcat • A JSP page can be as simple as an HTML page with a .jsp extension rather than .htm or .html • Place any new JSP files in the “webapps/ROOT” directory under your installed Tomcat directory. For example, to run “myfirst.jsp” file, copy the file into the “webapps/ROOT” directory and then open a browser to the address: 35
  • 36. Java and J2EE http://localhost:8080/myfirst.jsp This will show you the executed JSP file. JSP Tags - A JSP program consists of a combination of HTML tags and JSP tags. - JSP tags define java code that is to be executed before the output of the JSP program is sent to the browser. - A JSP tag begins with <% , which is followed by java code, and ends with %> - JSP tags are embedded into HTML component of s JSP program and are processed by a JSP virtual engine such as Tomcat. There are five types of JSP tags: 1. Comment tag 2. Declaration tag 3. Directive Tag 4. Expression tag 5. Scriptlet tag Comment tag: Describes the functionality of statements that follow the comment tag. Syntax: <%-- comment --%> Example: <%-- This JSP comment part will not be included in the response object --%> Declaration tag: This tag allows the developer to declare variables , objects and methods that will be used in Java Server Pages. Declaration tag starts with "<%!" and ends with "%>" surrounding the declaration. Syntax :- <%! declaration %> Examples <%! int var = 1; %> <%! int x, y ; %> <%! private int counter = 0 ; private String get Account ( int accountNo) ; 36
  • 37. Java and J2EE %> Directive Tag A directive tag commands the JSP virtual engine to perform a specific task such as importing a java packages required by objects and methods used in a declaration statement. Syntax of JSP directives is: <%@directive attribute="value" %> There are three directives: • <%@ page ... %> specifies information that affects the page • <%@ include ... %> includes a file at the location of the include directive (parsed) • <%@ taglib ... %> allows the use of custom tags in the page Examples: <%@ page import = “java.util.*” %> : imports the java.util package <%@ include file = “keogh/books.html %> : includes books.html file located in the the keogh directory <%@ taglib uri = “myTags.tld” %> : loads the myTags.tld library Expression tag: An expression tag contains a expression that is evaluated, converted to a String to get dipslayed Syntax is as follows <%= expression %> Example to show the current date and time. <%= new java.util.Date() %> Translated to out.println(new java.util.Date() ) Note: You cannot use a semicolon to end an expression Scriptlet tag: We can embed any amount of java code in the JSP scriplets. Syntax : <% //Java codes %> For example, to print a variable. <% String username = “visualbuilder” ; 37
  • 38. Java and J2EE out.println ( username ) ; %> Develop a JSP page that displays the current date and time Type the code below into a text file. Name the file Date.jsp. Place this in the correct directory on your Tomcat web server and call it via your browser. Date.jsp <html> <body> <center> <h3>Today is: <%= new java.util.Date() %> </h3> </center> </body> </html> Variables and objects With JSP declarations, we can declare variables that will be used later in the JSP expressions or scriplets. Example: A JSP program that declares and uses a variable var.jsp <html> <head> <title>My first JSP page </title> </head> <body> <%! int age = 29 %> <p> Your age is : <%= age %></p> 38
  • 39. Java and J2EE </body> </html> Example: Declaring multiple variables within a single JSP tag <html> <head> <title>JSP programming </title> </head> <body> <%! int age = 29 ; float salary; int empnumber; %> </body> </html> Example: Declaring objects and arrays within a single JSP tag <html> <head> <title>JSP programming </title> </head> <body> <%! String name ; String[ ] Telephone={ “201-555-1212”, “201-555-4433”}; String Company = new String(); 39
  • 40. Java and J2EE Vector Assignments = new Vector(); int[ ] Grade = { 100,82,93}; %> </body> </html> Methods Example: Defining and calling methods <html> <head> <title> JSP programming </title> </head> <body> <%! int curve(int grade) { return (10+grade); } %> Your curved grade is : <%= curve(80) %> </body></html> Control statements The primary method of flow control provided by JSP for designers are : • if/else statements. • switch statements These statements can check for something, such as the existence of a variable, and control what is output based on what it finds. Take a look at the following code: Example: JSP program using an if statement and a switch statement <html> <head> <title> JSP programming</title> 40
  • 41. Java and J2EE </head> <body> <%! int grade=70; %> <% if (grade >69) { %> <p> You passes! </p> <%} else { %> <p> Better luck next time. </p> <% } %> <% switch(grade) { case 90: %> <p> Your final grade is a A</p> <% break; case 80: %> <p> Your final grade is a B</p> <% break; case 70: %> <p> Your final grade is a C</p> <% break; case 60: %> <p> Your final grade is an F</p> <% break; } %> </body> </html> Note: The brackets ({}) are what contain the information relating to the appropriate if or else and switch condition. It seems odd in this case because the JSP scriptlet elements are separating the JSP code with the normal HTML code. So the start bracket is in the first JSP scriptlet: { %> and the end bracket is in another, with the output HTML in between: } %> The HTML in between will not be included in the HTML page output if the if or else and switch statement it belongs to is not the correct one. Only one, if or else and switch case, can be output. Loops Example: Using the for loop, while loop and the do..while loop to load HTML tables <html> 41
  • 42. Java and J2EE <head> <title> JSP programming</title> </head> <body> <%! int[ ] Grade={100,82, 93}; int x=0; %> <TABLE> <TR> <TD> First </TD> <TD> Second </TD> <TD> Third </TD> </TR> <TR> <% for (int i=1;i<3;i++) { %> <TD> <%= Grade[i] %> </TD> <% } %> </TR></TABLE> <TABLE> <TR> <TD> First </TD> <TD> Second </TD> <TD> Third </TD> </TR> <TR> <% while (x<3) { %> <TD> <%= Grade[x] %> </TD> <% x++; } %> </TR> </TABLE> <TABLE> <TR> <TD> First </TD> <TD> Second </TD> <TD> Third </TD> </TR> <TR> <% x=0; do { %> <TD> <%= Grade[x] %> </TD> <% x++; } while (x<3); %> </TR></TABLE></BODY></HTML> Request String 42
  • 43. Java and J2EE Retrieving the data (Request string) posted to a JSP file from HTML file is one of the most common functions in JSP page. Data(request string) is sent in a GET or POST request. . In a GET request the user request string consists of the URL and the query string(the data following the question mark on the URL. Here is an example of request string. http://www.jimkeogh.com/jsp/myprogram.jsp? Fname=”Bob”&lname=”smith” Retrieving the value of a specific field: The JSP program needs to parse this query string to extract the values of the fields that are to be processed by your JSP program. You can parse the query string by using the methods of the JSP request object. The getParameter() is the method used to parse a value of a specific field. getParameter() receives one argument, which is the name of the field whose value you want to receive. Example: Let us say you want to retrieve the value of the fname filed and the value of the lname filed in the request string. Here are the statements that you will need in your JSP program. <! String Firstname = request.getParameter(fname); String Lastname = request.getParameter(lname); %> In the above example, the first statement used the getParameter() method to copy the value of the fname from the request string and assign that value to the Firstname string object. Likewise the second statement performs a similar function. Retrieveing a value from a multivalued filed Retrieveing a value from a multivalued filed such as selection field shown in the figure can be very tricky since there are multiple instances of the field name, each with different value The getParameterValues() method is designed return multiple values from the field specified as an argument to the getParameterValues() Example: <% String[ ] Email=request.getParameterValues(“EMAILADDRESS”]; %> <p><%= EMAIL[0] %></p> 43
  • 44. Java and J2EE <p><%= EMAI[1] %></p> The name of the selection field is EMAILADDRESS, the values of which are copied into an array of String objects called EMAIL. Elements of the array are then displayed in JSP expression tag. Retrieving all field (parameter) names You can parse field names by using the getParameterNames() method. This method returns an enumeration of String objects that contain the field names in the request string. Later you can use the enumeration extracting methods ( such as nextElement(), hasMoreElements()) to copy the filed names to variables within your JSP progra. Write a JSP program which displays the first name and last name entered by the user from an HTML file HTML file <HTML> <HEAD> <TITLE>Handling HTTP GET request</TITLE> </HEAD> <BODY > <form method="get" action="http://localhost:8080/showname.jsp"> First Name<INPUT TYPE="TEXT" name="fname"><br> Last name<INPUT TYPE="TEXT" name="lname"> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> </HTML> <html><body><center> JSP file: <html> <body> <% String FirstName = request.getParameter("fname"); String LastName = request.getParameter("lname"); out.println("First Name="+FirstName+"<br>"); out.println("Last Name="+LastName); %> </body></html> Implicit objects The Objects available in any JSP without any need for explicit declarations are implicit objects. These predefined implicit objects are available in the expressions and scriplets of any JSP document. They are: 44
  • 45. Java and J2EE out: This object is instantiated implicitly from JSP Writer class and can be used for displaying anything within delimiters. For e.g. out.println(“Hi Buddy”); request: It is also an implicit object of class HttpServletRequest class and using this object request parameters can be accessed. For e.g. in case of retrieval of parameters from last form is as follows: request.getParameters(“Name”); Where “Name” is the form element. response: It is also an implicit object of class HttpServletResponse class and using this object response(sent back to browser) parameters can be modified or set. For e.g. in case of setting MIME type. response.setContentType(“text/html”); session: Session object is of class HttpSession and used to maintain the session information. It stores the information in Name-Value pair. For e.g. session.setValue(“Name”,”Jakes”); session.setValue(“Age”,”22”); Cookies 45
  • 46. Java and J2EE Example1 : Creating a cookie <html> <head> <title> JSP Programming </title> </head> <body> <%! String MyCookieName="UserID"; String MyCookieValue="JK1234"; Cookie cookie=new Cookie(MyCookieName,MyCookieValue); %> <% response.addCookie(cookie); out.println("My cookie has been set to"+ MyCookieName +"="+MyCookieValue); %> </body> </html> Example2: How to read a cookie <html> <head> <title> JSP Programming </title> </head> <body> <%! String MyCookieName="UserID"; String MyCookieValue, CName,CValue; int found=0, i=0; %> <% Cookie[] cookies=request.getCookies(); for(i=0;i < cookies.length;i++) { CName=cookies[i].getName(); CValue=cookies[i].getValue(); if(MyCookieName.equals(CName)) { found=1; MyCookieValue=CValue; } } if(found==1){ %> <p> Cookie name =<%= MyCookieName %> </p> <p> Cookie value =<%= MyCookieValue %> </p> <% } %> </body> </html> 46
  • 47. Java and J2EE JSP Sessions In any web application, the user moves from one page to another and it becomes necessary to track the user data through out the application. JSP provides an implicit object session which can be used to save the data specific to that particular user. Example1: How to create a session attribute <html> <head> <title> JSP Programming </title> </head> <body> <%! String AtName = “Product”; String AtValue=“1234”; session.setAttribute(AtName, AtValue); </body> </html> Example2: How to read session attribute <html> <head> <title> JSP Programming </title> </head> <body> <%! Enumeration e = request.getAttributesNames(); 47
  • 48. Java and J2EE while(e.hasMoreElements()) { String AtName = (String)e.nextElement(); String AtValue = (String)sesion.getAttribute(AtName); %> <p>Attribute Name <%= AtName %></p> <p>Attribute Value <%= AtValue %> </p> <% } %> </body> </html> Review Questions Q. What is JSP? How JSP differs from Java Servlets (5M) Q. How Does JSP work? or Q. Explain the JSP architecture? Q. What are the advantages of JSP? Q. Explain the life cycle methods of JSP? Q. List and Explain the different types of JSP tags (5M) Q. Explain the method of deployment of JSP with the Tomcat Q. Develop a JSP page that displays the current date and time Q. How can I declare variables and objects within my JSP page? Explain with example Q. How can I declare methods within my JSP page? Explain with example Q. How to use control statements in jsp code Q. How to use loops in JSP code Q. Explain how JSP handles request string posted from an HTML file or Q. Explain how JSP handles HTTP Get and Post request with example or Q. Write a JSP program which displays the first name and last name entered by the user from an HTML file Q. What are implicit objects? List them Q. What are cookies? How to set and display cookie in JSP? Q. Explain with example how to maintain sessions in JSP (5M) 48