Servlets Included in the J2EE
TOPICS• Servlet Basics
• Setting up the Servlet API
• Creating a Web Application
• The Servlet URL and the Invoking Web Page
• Servlet Structure
• Testing a Servlet
• Passing Data
• Sessions
• Cookies
• Accessing a Database Via a Servlet
What isStatic web page accessing
• www.xxx.yyy.x.html is given in IE
x.html
Dynamic Web Page
• NeedSuppose at server there is database of items and
stock,purchase details and server wants to make it available to the client via webpage
Server needs to process something and then generate the content
• Hence dynamic web page
Solutions for dynamic web page
• CGI(Common gateway interface)• Servlets and JSP• ASP• And many
What is CGIWhat is the disadv. Of CGI
• CommonGatewayInterfaces• Small programs requested by client and run on server to
generate dynamic content• Ex: upon submitting a form you may request a CGI program to
be executed and transfer entries entered by client in web page to DB at server.It can be in C++/Perl.
• But these run as separate processes at Webserver increasing load on web server
• Hence expensive interms of resources• They arenot platform independent• DB connection per client request
Why are servletsWhat are the adv?
• Improoved Performance• They run under the addressspace of web server ,
hence no separate process environment created per request
• Platform independent since written in java• Webservers from different vendors support servlets• It can communicate with applets,databases and
other s/w via sockets
What are servlets
• Servlets are java programs which run under the control of web server to help it to generate dynamic web page
ServletLifeCycle• Three methods are central to the life cycle of any servlet.They are implemented by
every servlet and are called at specific times by web server(servlet container).
• User enters URL in a Webbrowser• Browser genearates an HTTP request and sends to the web server• The webserver upon receipt of this request maps this to the particular servlet• Then that servlet class is loaded and method init() is called• This method is called only once during lifetime of servlet• Init is helpful for configuring and setting initial parameters• The webserver calls service() next• This method actually processes HttpRequest and builds HttpResponse Object• For each client request a call to service is made • When server decides to shutdown or unload servlet it calls destroy() method• The code inside this relinquishes resources such as filehandlers
Steps forWriting your own servlet
• Installing required s/w ‘s refer other slides named servletinstallinfo.ppt
• Once everything is set then 1. create and compile the servlet source code 2. start webserver 3.start a web browser and request the servlet
A simple HelloServlet• import java.io.*; • import javax.servlet.*; • • public class HelloServlet extends GenericServlet• { • • public void service(ServletRequest request, ServletResponse response) • throws ServletException, IOException• { • response.setContentType("text/html"); • PrintWriter pw = response.getWriter(); • pw.println("<B>Hello!"); • pw.close(); • } • }
• The GenericServlet class provides functionality that simplifies the creation of a servlet. For example, it provides versions of init( ) and destroy( ), which may be used as it is. You need supply only the service( ) method.
• Inside HelloServlet service method is overridden.
• This method handles request from client
• Notice that the first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client request.
• The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
• The call to setContentType( ) establishes the MIME type of the HTTP response. In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML source code.
• Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is
sent to the client as part of the HTTP response. Then println( ) is used to write some simple HTML source code as the HTTP response.
Downloading and configering webserver
• From Apache site download Tomcat6.0 binary file and unzip(extract) it to say /home/student.
• It creates a directory named apachetomcat-versionnumber.
• Now goto lib subfolder of apachetomcat directory and see if servlet-api.jar is present.
• Copy this jar file to your student directory
Compilation
• Javac HelloServlet.java -classpath \home\student\servlet-api.jar
• Above step compiles your servlet code.• Now transfer your servlet’s class file to the
directory apachetomcat-versionnumber\webapps\examples\WEB-INF\classes
• In the WEB-INF directory there is an XML file called web.xml
• Add the following in web.xml file• <servlet>• <servlet-name>HelloServlet</servlet-name>• <servlet-class>HelloServlet</servlet-class>• </servlet>• <servlet-mapping>• <servlet-name>HelloServlet</servlet-name>• <url-pattern>/servlet/HelloServlet</url-pattern>• </servlet-mapping>
• Start Tomcat• Start Tomcat server by running startup.sh file from bin
directory of tomcat6.0. Tomcat must be running before you try to execute a servlet.
You can check if tomcat is running by typing http://localhost:8080 in webbrowser and see that it will open homepage of tomcat.
• Start a Web Browser and Request the Servlet• Start a web browser and enter the URL shown here:• http://localhost:8080/examples/servlet/HelloServlet• Alternatively, you may enter the URL shown here:• http://127.0.0.1:8080/examples/servlet/HelloServlet
The Servlet API• Two packages contain the classes and
interfaces that are required to build servlets. – javax.servlet– javax.servlet.http.
• They constitute the Servlet API.
04/18/23 DEPT OF CSE 19
The javax.servlet Package
04/18/23 DEPT OF CSE 20
Classes in the servlet package
04/18/23 DEPT OF CSE 21
Methods in servlet package
04/18/23 DEPT OF CSE 22
Servlet Interface• All servlet 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- invoked by the server
• getServletConfig() method is called by the servlet to obtain initialization parameters
• getServletInfo() is overridden to provide with iuseful information
04/18/23 DEPT OF CSE 23
Methods in Servlet
04/18/23 DEPT OF CSE 24
Servlet Config Interface• This allows a servlet to obtain configuration
data when it is loaded
04/18/23 DEPT OF CSE 25
The Servlet Context Interface
04/18/23 DEPT OF CSE 26
Enables servlets to obtain information about their environment
ServletRequest and ServletResponse Interface
• Enables a servlet to obtain information about a client request
• Enables servlet to formulate a response for a client
04/18/23 DEPT OF CSE 27
Methods defined by ServletRequest
04/18/23 DEPT OF CSE 28
Methods defined by ServletResponse
04/18/23 DEPT OF CSE 29
Generic Servlet Class• Provides implementations of the basic life cycle
methods for a servlet.• Implements the Servlet and ServletConfig interfaces• Method to append a string to the server log file is
available– void log(String s)– void log(String s, Throwable e)– s is the string to be appended to the log, and e is an
exception that occurred.
04/18/23 DEPT OF CSE 30
The ServletInputStream Class• The ServletInputStream class extends InputStream.• It is implemented by the servlet container and provides an
input stream that a servlet developer can use to read the data from a client request.
• It defines the default constructor. • Method is provided to read bytes from the stream. – int readLine(byte[ ] buffer, int offset, int size) throws IOException– buffer is the array into which size bytes are placed starting at
offset. The method returns the actual number of bytes read or –1 if an end-of-stream condition is encountered.
04/18/23 DEPT OF CSE 31
The ServletOutputStream Class
• The ServletOutputStream class extends OutputStream.
• It is implemented by the servlet container and provides an output stream that a servlet developer can use to write data to a client response.
• A default constructor is defined. • It also defines the print( ) and println( ) methods,
which output data to the stream.
04/18/23 DEPT OF CSE 32
The Servlet Exception Classes
• javax.servlet defines two exceptions.• The first is ServletException, which indicates
that a servlet problem has occurred. • Second is UnavailableException, which
extends ServletException It indicates that a servlet is unavailable.
04/18/23 DEPT OF CSE 33
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
04/18/23 DEPT OF CSE 34
<html><body><center><form name="Form1“ method="post“ action="http://localhost:8080/servlets-examples/servlet/PostParametersServlet"><table><tr><td><B>Employee</td><td><input type=textbox name="e" size="25" value=""></td></tr><tr><td><B>Phone</td><td><input type=textbox name="p" size="25" value=""></td></tr></table><input type=submit value="Submit"></body></html>
04/18/23 DEPT OF CSE 35
import java.io.*;import java.util.*;import javax.servlet.*;public class PostParametersServletextends GenericServlet {public void service(ServletRequest request,ServletResponse response)throws ServletException, IOException {// Get print writer.PrintWriter pw = response.getWriter();// Get enumeration of parameter names.Enumeration e = request.getParameterNames();// Display parameter names and values.while(e.hasMoreElements()) {String pname = (String)e.nextElement();pw.print(pname + " = ");String pvalue = request.getParameter(pname);pw.println(pvalue); }pw.close(); } }
04/18/23 DEPT OF CSE 36
The javax.servlet.http Package
04/18/23 DEPT OF CSE 37
Class provided in the javax.servlet.http Package
04/18/23 DEPT OF CSE 38
The HttpServletRequest and HttpServletResponse Interface Interface
• The HttpServletRequest interface enables a servlet to obtain information about a client request.
• The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
• Constants that correspond to the different status codes that can be assigned to an HTTP response.– SC_OK indicates that the HTTP request succeeded– SC_NOT_FOUND indicates that the requested resource is
not available.04/18/23 DEPT OF CSE 39
04/18/23 DEPT OF CSE 40
04/18/23 DEPT OF CSE 41
The HttpSession Interface
• The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP session.
• The methods throw an IllegalStateException if the session has already been invalidated.
04/18/23 DEPT OF CSE 42
04/18/23 DEPT OF CSE 43
The HttpSessionBindingListener Interface
• The HttpSessionBindingListener interface is implemented by objects that need to be notified when they are bound to or unbound from an HTTP session.
• The methods that are invoked when an object is bound or unbound – void valueBound(HttpSessionBindingEvent e)– void valueUnbound(HttpSessionBindingEvent e)– e is the event object that describes the binding.
04/18/23 DEPT OF CSE 44
The Cookie Class• The Cookie class encapsulates a cookie.• A cookie is stored on a client and contains state information. • Cookies are valuable for tracking user activities.• The user does not need to enter this data each time he or she
visits the store.• Aservlet can write a cookie to a user’s machine via the
addCookie( ) method of the• HttpServletResponse interface. The data for that cookie is then
included in the header of the HTTP response that is sent to the browser.
04/18/23 DEPT OF CSE 45
• The names and values of cookies are stored on the user’s machine. • The information that is saved for each cookie
• The name of the cookie• The value of the cookie• The expiration date of the cookie• The domain and path of the cookie
• The expiration date determines when this cookie is deleted from the user’s machine.
• If an expiration date is not explicitly assigned to a cookie, it is deleted when the current browser session ends.
• Otherwise, the cookie is saved in a file on the user’s machine.
04/18/23 DEPT OF CSE 46
• The domain and path of the cookie determine when it is included in the header of an HTTP request.
• If the user enters a URL whose domain and path match these values, the cookie is then supplied to the Web server.
• Otherwise, it is not.• There is one constructor for Cookie. It has the signature
shown here:– Cookie(String name, String value)– Name and value of the cookie are supplied as arguments to the
constructor
04/18/23 DEPT OF CSE 47
04/18/23 DEPT OF CSE 48
The HttpServlet Class• The HttpServlet class extends GenericServlet.• It is commonly used when developing servlets that
receive and process HTTP requests.
04/18/23 DEPT OF CSE 49
04/18/23 DEPT OF CSE 50
The HttpSessionEvent Class• HttpSessionEvent encapsulates session events.• It extends EventObject and is generated when a
change occurs to the session. – HttpSessionEvent(HttpSession session)– session is the source of the event.– HttpSessionEvent defines one method, getSession( )– HttpSession getSession( )– It returns the session in which the event occurred.
04/18/23 DEPT OF CSE 51
04/18/23 DEPT OF CSE 52
The HttpSessionBindingEvent Class• The HttpSessionBindingEvent class extends HttpSessionEvent.
It is generated when a listener is bound to or unbound from a value in an HttpSession object.
• It is also generated when an attribute is bound or unbound. Here are its constructors:– HttpSessionBindingEvent(HttpSession session, String name)– HttpSessionBindingEvent(HttpSession session, String name, Object val)– Here, session is the source of the event, and name is the name associated
with the object that is– being bound or unbound. If an attribute is being bound or unbound, its
value is passed in val.
04/18/23 DEPT OF CSE 53
• The getName( ) method obtains the name that is being bound or unbound. – String getName( )
• The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound:– HttpSession getSession( )
• The getValue( ) method obtains the value of the attribute that is being bound or unbound.– Object getValue( )
04/18/23 DEPT OF CSE 54
Handling HTTP Requests and Responses
• The HttpServlet class provides specialized methods that handle the various types of HTTP requests.
• doDelete( ), doGet( ), doHead( ), doOptions( ), doPost( ), doPut( ), and doTrace( ).
04/18/23 DEPT OF CSE 55
Handling HTTP GET Requests<html><body><center><form name="Form1"action="http://localhost:8080/servlets-examples/servlet/ColorGetServlet"><B>Color:</B><select name="color" size="1"><option value="Red">Red</option><option value="Green">Green</option><option value="Blue">Blue</option></select><br><br><input type=submit value="Submit"></form></body></html>
04/18/23 DEPT OF CSE 56
import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class ColorGetServlet extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {String color = request.getParameter("color");response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("<B>The selected color is: ");pw.println(color);pw.close(); } }
04/18/23 DEPT OF CSE 57
Handling HTTP POST Requests<html><body><center><form name="Form1"method="post"action="http://localhost:8080/servlets-examples/servlet/ColorPostServlet"><B>Color:</B><select name="color" size="1"><option value="Red">Red</option><option value="Green">Green</option><option value="Blue">Blue</option></select><br><br><input type=submit value="Submit"></form></body></html>
04/18/23 DEPT OF CSE 58
import javax.servlet.*;import javax.servlet.http.*;public class ColorPostServlet extends HttpServlet {public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {String color = request.getParameter("color");response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("<B>The selected color is: ");pw.println(color);pw.close();}}
04/18/23 DEPT OF CSE 59
Creating a Web Application
A Simple Example
Create the following HTML document
Servlet Structure
• Servlets must import the following two packages
1. javax.servlet
2. javax.servlet.http
• Servlets must extend class HttpServlet from package
java.servlet.http.
• Two most common HTTP requests
1. GET (for multiple data items)
2. POST (for single items)
Servlet Structure
• At the servlet end, method service will despatch either
method doGet or method doPost in response to these
requests
• All three methods have a void return type and take the following
two arguments:
1. An HttpServletRequest object;
2. An HttpServletResponse object.
Servlet Structure
• HttpServletResponse object has two methods
1. void setContentType(String <type>)
• specifies the data type of the response.
• Normally, this will be "text/HTML".
2. PrintWriter getWriter()
• Returns the output stream object to which the servlet can
write character data to the client.
Servlet Structure
• There are four basic steps in a servlet...
1. Execute the setContentType method with an argument of
"text/HTML".
2. Execute the getWriter method to generate a PrintWriter
object.
3. Retrieve any parameter(s) from the initial Web page.
4. Use the println method of the above PrintWriter object to
create elements of the Web page to be 'served up' by our
Web server.
First servlet
First servlet
Passing Data
Passing Data
Passing Data
• The methods of HttpServletRequest that are responsible for
handling values/parameters received by servlets are listed
below
Passing Data
Passing Data
Passing Datainitial page
Passing Dataservlet-generated
Passing DataHow to force the browser to reload the original page, rather than
retrieve it from its cache, when a return is made to this page.?
There is an HTML META tag that will do this, but the tag varies
from browser to browser.
Passing DataHow to force the browser to reload the original page, rather than
retrieve it from its cache, when a return is made to this page.?
There is an HTML META tag that will do this, but the tag varies
from browser to browser.
These should be placed immediately after the <HEAD> tag on the initial Web page
Passing DataAccepting two numbers, adds them and then displays the result
Passing DataAccepting two numbers, adds them and then displays the result
Accepting two numbers, adds them and then displays the result
• user may enter a non-numeric value, the servlet must cater
for a possible NumberFormatException.
• method getParameter will need to convert the strings it
receives into integers by using the parseInt
Sessions
Why Sessions?• HTTP is that it is a stateless protocol
• Each request and each response is a self contained
and independent transaction
• A session is a container where data about a client's
activities may be stored and accessed by any of the
servlets that have access to the session object.
Why Sessions?
• A session object is created by means of the
getSession ()method of HttpServletRequest
• the server returns the current session if there is one; otherwise, it creates a new session object.
For example:
Why Sessions?
• A session object contains a set of name-value
pairs.
• Each name is of type String and each value is of type Object.
• Note that objects added to a session must implement the
Serializable interface.
• A servlet may add information to a session object via the
following method:
Why Sessions?
• A session object contains a set of name-value
pairs.
Why Sessions?
Why Sessions?
Why Sessions?
HTML file
HTML file
HTML file
HTML page
Selection servlet
Selection servlet
Selection servlet
Selection servlet
Selection servlet
Selection servlet
Selection servlet
Initial Page
Weight servlet
Weight servlet
Weight servlet
Weight servlet
Weight servlet
Checkout servlet
Checkout servlet
Checkout servlet
Checkout servlet
Checkout servlet
Checkout servlet
Checkout page
What is a Cookie?
• A cookie is an associated name-value pair in which
both name and value are strings.
• Each cookie is held in a small file sent by the server to
the client machine
• It is retrieved by the server on subsequent visits by
the user to the site.
What is a Cookie?
• The constructor for a Java Cookie object must have this
signature
• Once created, it must be added to the HttpServletResponse
object via the following HttpServletResponse method :
What is a Cookie?
• Cookies are retrieved via the following method of class
HttpServletRequest
What is a Cookie?
setMaxAge method• Specifies the number of seconds for which the cookie will
remain in existence
• If any negative value is specified, then the cookie goes out of
existence when the client browser leaves the site
• A value of zero causes the cookie's immediate destruction.
Example - CookieAdder
Example
Example
Example
Example - GetPreferences
Example
Example
Example
ShowSum Servlet
ShowSum Servlet
ShowSum Servlet
ShowSum Servlet
ShowSum Servlet
ShowSum Servlet
ShowSum Page
Accessing a Database Via a Servlet
Example
Example
servlet DbServlet
servlet DbServlet
servlet DbServlet
servlet DbServlet
servlet DbServlet
servlet DbServlet
servlet DbServlet
servlet DbServlet
servlet DbServlet