You are on page 1of 23

What is a Servlet?

Servlet?
 Servlets are Java programs that serve as an
intermediating layer between an HTTP request of a
client and applications in the Web server
 Programs that runs on the server:
Should sometimes access a database
Java Servlet Programming Should sometimes access the file system
Should create of Web pages online
Khalid Raza
Department Computer Science  A servlet is a dynamically loaded module that
Jamia Millia Islamia (Central University) services requests from a Web server
New Delhi-110025  A servlet runs entirely inside the JVM
kraza@jmi.ac.in | www.kraza.in

Using Servlets Supporting Sevlets


 Reading the data that the user sent (HTTP request)
 Receiving information from the HTTP request  The Web server must support servlets:
 Running an application with respect to the given input Apache Tomcat
 The application creates a document for the response Suns JavaServer Web Development Kit
(e.g., HTML document) (JSWDK)
 Parameters are defined for the HTTP response Allaire Jrun an engeine that can be added
 The created document is sent to the user to IIS, PWS, old Apache Web servers etc
Suns Java Web Server

3 4
Working with Tomcat Definitions and Configuration
 Definition files are in the directory
 In the installation directory:
tomcat_home/conf/
Use the command tomcat start to start the
server  The definition of the port number of the server is
Use the command tomcat stop to stop the in the file tomcat_home/conf/server.xml
server
Changing Port: server.xml
You get to the server by requesting on a web
browser http://<host>:port/ <!-- Normal HTTP -->
<Connector className=
 Host is the machine on which you started tomcat
"org.apache.tomcat.service.PoolTcpConnector">
 Port is the port number according to the <Parameter name="handler"
configuration value="org.apache.tomcat.service.
http.HttpConnectionHandler"/>
<Parameter name="port"
value="8080"/>
</Connector>
5 6

MIME--Types Mappings
MIME Servlets Class Files
 Place for the servlet files:
tomcat_home/conf/web.xml
tomcat_home/webapps/ROOT/WEB-
INF/classes
<mime-mapping>  Standard place for servlet classes
<extension>txt</extension> tomcat_home/user_dir/WEB-INF/classes
<mime-type>text/plain</mime-type>
 User defined position for servlet classes
</mime-mapping>
<mime-mapping> tomcat_home/lib
<extension>html</extension>  Position for JAR files with classes
<mime-type>text/html</mime-type>
</mime-mapping>

7 8
User Defined Directories Mapping Directories
 The definition is in the file server.xml inside the
tag <ContextManager >, <Context path="/dbi"
docBase="webapps/dbi"
<Context path="/dbi" >
docBase="webapps/dbi" </Context>
crossContext=true"
debug="0"
http://host:8080/dbi/servlet/MyServlet
reloadable="true" >
</Context>

tomcat_home/webapps/dbi/
WEB-INF/classes/MyServlet.class

9 10

Servlet Package
 javax.servlet
 The Servlet interface defines Architecture
methods that manage servlets
and their communication with
Working with Servlets clients Servlet

 Client Interaction: when it


accepts call, receives two objects
Generic Servlet
that implements
ServletRequest
ServletResponse HttpServlet

YourOwnServlet
11 12
Creating a Servlet Creating a Servlet
Extend HTTPServlet
Implement doGet ServletRequest HTTPServletRequest

Implement doPost

The methods
should get an input (the HTTP request) Implement doGet
Should create an output (the HTTP response)
Implement doPost

ServletResponse HTTPServletResponse
13 14

import java.io.*;
Hello World Example Compiling
import javax.servlet.*;
import javax.servlet.http.*;
 In order to compile a servlet, you may need to add to your
CLATHPATH definition the following:
public class HelloWorld extends HttpServlet setenv CLASSPATH ${CLASSPATH}:
{ /usr/local/java/apache/jakarta-
public void doGet(HttpServletRequest req, tomcat/lib/ant.jar:
HttpServletResponse res) throws ServletException,
IOException /usr/local/java/apache/jakarta-
{ tomcat/lib/jasper.jar:
res.setContentType("text/html"); /usr/local/java/apache/jakarta-
PrintWriter out = res.getWriter(); tomcat/lib/jaxp.jar:
/usr/local/java/apache/jakarta-
out.println("<HTML><HEAD><TITLE>Hello
World</TITLE></HEAD>");
tomcat/lib/parser.jar:
out.println(<BODY><BIG>Hello World /usr/local/java/apache/jakarta-
</BIG></BODY></HTML>"); tomcat/lib/servlet.jar:
out.close(); /usr/local/java/apache/jakarta-tomcat/
} lib/webserver.jar
}
15 16
Calling the Servlet Servlet Life Cycle
 Calling the servlet is done from the Web browser:  No main() method!
http://host:port/servlet/ServletName  The server loads and initializes the servlet
 The servlet handles client requests
For servlets that are positioned under  The server can remove the servlet
webapps/ROOT/WEB-INF/classes  The servlet can remain loaded to handle additional
requests
 Incur startup costs only once

17 18

Servlet Life Cycle Servlet Lifecycle


No Concurrency Issue
Server loads Servlets Server runs init only once,
Servicing requests by
calling the
- run init method not per request
service method
Calling the
init method Servlets Accept Request from service must be thread-safe
Clients and return Data back - multiple service method at a time
Destroying the servlet - run service method if that is impossible, servlet must
ServletConfig by calling the implement SingleThreadModel interface
destroy method
Initialization
and Loading Server removes Servlets
- run destroy method destroy must be thread-safe
- when server runs destroy, other threads
might be accessing shared resources
Garbage Server reloads Servlets
Servlet Class Collection
- run init method
19
A Typical Servlet Lifecycle HTTP Methods
 POST:
Data sent in two steps
Designed for Posting information
 Browser contacts server
 Sends data
 GET:
Contacts server and sends data in single step
Appends data to action URL separated by
question mark
Designed to get information
from Servlet Essential 1.3.5 by Stefan Zeiger
http://www.novocode.com/doc/servlet-essentials/
22

Other Methods Servicing a Servlet


 HEAD: Client sees only header of response to  Every call to the servlet creates a new thread that
calls the service method
determine size, etc
 The service methods check the type of request
 PUT: Place documents directly on server (GET, POST, PUT, DELETE, TRACE, OPTION) and
 DELETE: Opposite of PUT call the appropriate method: doGet, doPost,
 TRACE: Debugging aid returns to client doPut, doDelete, DoTrace, doOption
contents of its request  It is recommended to implement doPost and doGet
instead of implementing service. Why?
 OPTIONS: what options available on server
 The method doPost can call doGet in order to
reuse code

23 24
HttpServlet Request Handling Important Note
 When you change the servlet, usually it is not
Web
HttpServlet subclass enough just to compile it why?
Server
GET request  What should you do?
doGet()  You need to stop tomcat and restart tomcat to
make tomcat reload the servlet and not use the old
response
version stored in memory
service()
POST request

doPost()

response

25 26

Starting Servlets The Configuration Parameters


 Initialization:  The configuration parameters are taken
Servlets init(ServletConfig) or init() methods from the file web.xml that is under
Called when the servlet is called for the first tomcat_home/dir_path/WEB-INF/
time from a client
A code for initialization that is called only once
(e.g., creating the tables of the database)
Initialization parameters are server specific

27 28
<?xml version="1.0" encoding="ISO-8859-1"?>
import java.io.*;
import javax.servlet.*;
<!DOCTYPE web-app import javax.servlet.http.*;
PUBLIC "-//Sun Microsystems,Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd"> /**
<web-app> *Example using servlet initialization.
<servlet> */
<servlet-name>InitExample</servlet-name>
<servlet-class>ServletInit</servlet-class> public class ServletInit extends HttpServlet {

<init-param> String dbiUrl, dbUrl;


<param-name>dbi</param-name>
<param-value>http://www.cs.huji.ac.il/~dbi</param-value> public void init(ServletConfig config)
</init-param> throws ServletException {
<init-param> // Always call super.init
<param-name>db</param-name> super.init(config);
<param-value>http://www.cs.huji.ac.il/~db</param-value> dbiUrl = config.getInitParameter("dbi");
</init-param>
dbUrl = config.getInitParameter("db");
</servlet>
}
</web-app>

29 30

public void doGet(HttpServletRequest request,


HttpServletResponse response)
Destroying Servlets
throws ServletException, IOException {
response.setContentType("text/html");  Destroying:
PrintWriter out = response.getWriter(); destroy() method
String title = "Initialization Example 2";
out.println("<HTML><HEAD>"); make sure all service threads complete
out.println("<TITLE>"+title+"</TITLE></HEAD>");
out.println("<BODY><H1>Links to courses</H1>");
out.println("<TABLE><TR><TH>Course);
out.println(</TH><TH>Link</TH></TR>");
out.println("<TR><TD>dbi</TD><TD>"+dbiUrl+"</TD></TR>");
out.println("<TR><TD>db</TD><TD>"+dbUrl+"</TD></TR>");
out.println("</TABLE></BODY></HTML>");
}
}

31 32
Example Counting Threads
Maintaining the Count
public ShutdownExample extends HttpServlet {
private int serviceCounter = 0; protected void service(HttpServletRequest req,
... HttpServletResponse resp)
//Access methods for serviceCounter throws ServletException, IOException
protected synchronized void enteringServiceMethod() {
{ enteringServiceMethod();
serviceCounter++;
} try {
protected synchronized void leavingServiceMethod() super.service(req, resp);
{ } finally {
serviceCounter--; leavingServiceMethod();
} }
protected synchronized int numServices() { }
return serviceCounter;
}
}

33 34

Notifying a Shutdown A Destroy Example


public ShutdownExample extends HttpServlet { public void destroy() {
private boolean shuttingDown;
/* Check to see whether there are still
... * service methods running,
//Access methods for shuttingDown * and if there are, tell them to stop.
protected setShuttingDown(boolean flag) { */
shuttingDown = flag; if (numServices() > 0) {
} setShuttingDown(true);
protected boolean isShuttingDown() { }
return shuttingDown;
} /* Wait for the service methods to stop. */
} while(numServices() > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {}
}
}

35 36
Handling a User Request
 The servlet gets parameters from HTML forms
HTML Forms
 <form action= method=> </form>
comprise a single form
Getting Input From the User action the name of the processing server
method the HTTP method to use when passing
parameters to the server
enctype the encription used to send the
parameters

37 38

The <input> Tag Getting the Parameters Values


 Inside a form, INPUT tags define fields for data entry
 Standard input types include: buttons, checkboxes, request.getParameter(x);
password field, radio buttons, text fields, image-buttons,
request.getParameter(y);
text areas, hidden fields, etc.
<HTML>
If there can be multiple values for the parameter, use
<form method=GET
action=http://pita.cs.huji.ac.il:8090/servlet/update> getParameterValues

<INPUT name=x type=text> If you dont know the names of the parameters, use
<INPUT name=y type=text>
<INPUT type=submit> <INPUT type=reset> getParameterNames
</form>

</HTML>

http://pita.cs.huji.ac.il:8090/servlet/update?x=19&y=104 39 40
<HTML>
<HEAD>
<TITLE>Sending Parameters</TITLE>
</HEAD>
<BODY BGCOLOR="#CC90E0">
<H1 ALIGN="LEFT">Please enter the parameters</H1>
<FORM ACTION=dbi/servlet/SetColors METHOD=GET>
<TABLE>
<TR><TD>Background color:</TD>
<TD><INPUT TYPE="TEXT" NAME="bgcolor"></TD></TR>
<TR><TD>Font color:</TD>
<TD><INPUT TYPE="TEXT" NAME="fgcolor"></TD></TR>
<TR><TD>Font size:</TD>
<TD><INPUT TYPE="TEXT" NAME="size"></TD></TR>
</TABLE>
<BR> http://pita.cs.huji.ac.il:8080/colors.html
<INPUT TYPE="SUBMIT" VALUE="Show Page">
</FORM>

</BODY>
tomcat_home/webapps/ROOT/colors.html
</HTML> 41 42

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

/**
* Creates a page according to the parameters
* given from a form
*/

public class SetColors extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

String title = "Set Colors Example";


response.setContentType("text/html");
http://pita.cs.huji.ac.il:8080/dbi/servlet/ PrintWriter out = response.getWriter();
SetColors?bgcolor=wheat&fgcolor=blue&size=5
String bg = request.getParameter("bgcolor");
String fg = request.getParameter("fgcolor");
String size = request.getParameter("size");

43 44
Handling Post
out.println("<HTML><HEAD><TITLE>" + title +
"</TITLE></HEAD>");
out.println("<BODY text='" + fg + <FORM ACTION=dbi/servlet/SetColors METHOD=POST>
"' bgcolor='" + bg + "'>");
out.println("<H1>" + title + "</H1>");
out.println("<FONT size='" + size + "'>");
out.println("You requested a background color " + public void doPost(HttpServletRequest request,
bg + "<P>"); HttpServletResponse response)
out.println("You requested a font color " + throws ServletException, IOException {
fg + "<P>");
out.println("You requested a font size " + doGet(request, response);
size + "<P>"); }
out.println("</FONT></BODY></HTML>");
}
}

45 46

import java.io.*;
Information on Client Request import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
request.getHeader(Accept);
/**
* Shows the request headers sent on the request
request.getHeaderNames(); */

public class ShowRequestHeaders extends HttpServlet {


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

PrintWriter out = response.getWriter();
String title = "Servlet Example:
Showing Request Headers";

47 48
out.println("<HTML><HEAD><TITLE>" + title +
"</TITLE></HEAD>" +
"<BODY BGCOLOR=\"#AACCAA\" TEXT=\"#990000\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n" +
"<B>Request Method: </B>" +
request.getMethod() + "<BR>\n" +
"<B>Request URI: </B>" + /** Let the same servlet handle both GET and POST. */
request.getRequestURI() + "<BR>\n" +
"<B>Request Protocol: </B>" + public void doPost(HttpServletRequest request,
request.getProtocol() + "<BR><BR>\n" + HttpServletResponse response)
"<TABLE BORDER=1 ALIGN=CENTER>\n" + throws ServletException, IOException {
"<TR BGCOLOR=\"#88AA88\">\n" + doGet(request, response);
"<TH>Header Name<TH>Header Value"); }
Enumeration headerNames = request.getHeaderNames(); }
while(headerNames.hasMoreElements()) {
String headerName =
(String)headerNames.nextElement();
out.println("<TR><TD>" + headerName);
out.println("<TD>+request.getHeader(headerName));
}
out.println("</TABLE>\n</BODY></HTML>");
49 50
}

Creating the Response of the Servlet

51 52
HTTP Response Setting the Response Status
 The response includes:  The status code of the HTTP response can be set by the
Status line: version, status code, status message setStatus method of HTTPServletResponse
Response headers  setStatus(int)
Empty line
 The status should be defined before sending content
Document
through the PrintWriter of the
HTTPServletResponse
HTTP/1.1 200 OK  The status can be defined after setting headers of the
Content-Type: text/plain HTTPServletResponse

Bla Bla Bla

53 54

Setting Response Headers More Headers Methods


 Headers can be defined  You can use
using setHeader(String header, String containsHeader to check existence of a
value) of HTTPServletResponse header in the response
using setIntHeader(String header, int setContentType
value) setContentLength
using setDateHeader(String header, addCookie
long milliseconds) (translate to GMT)
 The headers must be defined before the first time the
buffer content is sent

55 56
Automatic Responses Using Redirect
 You can create a servlet that
 An automatic response is created by Gets a url from a user (e.g., from a form)
sendError(int code, String message) Return a redirect message with the given url
 Returns the status code with the message
 Or
 Usually status code 404
(HTTPServletResponse.SC_NOT_FOUND)
Get a list of words from the user
sendRedirect(String url) Return a redirect message to a search engine
with the given words as parameters
 Creates a response with status code 302
(HTTPServletResponse.SC_MOVED_TEMPORARILY)
with a Location header that includes the given url

57 58

Buffer Session Tracking


 HTTP is a stateless protocol: each time a
client retrieves a Web page, the client opens a
Servlet separate connection and the server does not
Buffer automatically maintain contextual information
server
about the client.
response

setBufferSize  There are three typical solutions to this problem:


getBufferSize Cookies,
isComitted
flushBuffer
request URL rewriting,
client
reset Hidden form fields

59
Session Tracking Session Tracking

Request
Session ID = 123XYZ Session ID = 123XYZ

Amazon Shopping Cart sc Amazon Shopping Cart sc


[item 1=324] [item 1=324]

Response:
Set-Cookie: sid=123XYZ
Servlet Container Servlet Container

Session Tracking Session Tracking

Request: Request:
Set-Cookie: sid=123XYZ Set-Cookie: sid=123XYZ
Session ID = 123XYZ
Session ID = 123XYZ
Shopping Cart sc
Amazon Shopping Cart sc Amazon [item 1=324]
[item 1=324]
[item 2=115]

Servlet Container Servlet Container


Using Cookies Using Cookies (Example)
// CookieDemo.java
 A cookie is a bit of information sent by a web
server to a browser that can later be read back // This servlet uses a cookie to determine when the last visit by this
from that browser. // browser occurred. It makes use of the VisitTracker object.

 The server can take that bit of information and use // Cookies normally expire as soon as the browser exits.
// We want the cookie to last one year and so we use
it as a key to recover information about prior visits. // setMaxAge(seconds) on the cookie.
 Cookies are read from the request object by calling
import java.io.*;
getCookies() on the request object. import java.util.*;
 Cookies are placed in the browser by calling import javax.servlet.*;
import javax.servlet.http.*;
addCookie() on the response object.

public class CookieDemo extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse res) if (id == null) {
throws ServletException, IOException { // They have not been here before and need a cookie.
res.setContentType("text/plain");
PrintWriter out = res.getWriter(); String uid = new java.rmi.server.UID().toString();
id = java.net.URLEncoder.encode(uid);
Cookie[] c = req.getCookies(); Cookie c1 = new Cookie("cookiedemouser", id);
// If this person has been here before then we should have c1.setMaxAge(60*60*24*365);
// a cookiedemouser field assigned to a unique id. res.addCookie(c1);
}
String id = null;
VisitTracker visit = VisitTracker.getInstance();
if (c!=null) { // we may have the cookie Date last = visit.lastVisit(id);
for (int i=0; i<c.length; i++) { if(last == null)
if (c[i].getName().equals("cookiedemouser")) { out.println("Welcome, you were never here before");
id = c[i].getValue(); else
} out.println("Your last visit was on " + last);
break; visit.addVisit(id);
} }
} }
URL Rewriting URL Rewriting
 With this approach, the client appends some extra
data on the end of each URL.  URL rewriting has the same drawback as do
cookies, namely, that the server-side program has a
 That data identifies the session, and the server
lot of straightforward but tedious processing to do.
associates that identifier with user-specific data it has
stored.  Even with a high-level API that handles most of the
details, we have to be very careful that every URL
 E.g. http://host/path/file.html;jsessionid=a1234,
that references our site and is returned to the user
the session identifier is attached as jsessionid=a1234,
(even by indirect means like Location fields in
so a1234 is the ID that uniquely identifies the table of
server redirects) has the extra information
data associated with that user.
appended.
 URL rewriting is a moderately good solution for
 This restriction means that you cannot have any
session tracking and even has the advantage that it
static HTML pages on your site.
works when browsers dont support cookies or when
the user has disabled them.

Hidden Form Fields Hidden Form Fields


 <input type=hidden name=session value=a1234>  When the form is submitted, the specified name and
value are automatically included in the GET or POST
data.
 The major disadvantage is that it only works if every
page is dynamically generated by a form submission.
 Clicking on a regular (<A HREF...>) hypertext link
does not result in a form submission,
 Hence, hidden form fields cannot support general
session tracking, only tracking within a specific series
of operations such as checking out at a store.
Java HttpSession API Solution Java HttpSession API Solution
 Using sessions in servlets is straightforward and involves four
 Servlets provide an outstanding session-tracking solution: basic steps.
the HttpSession API. 1. Accessing the session object associated with the
 This high-level interface is built on top of cookies or URL current request. Call request.getSession() to get an
rewriting. HttpSession object, which is a simple hash table for storing
user-specific data.
 All servers are required to support session tracking with 2. Looking up information associated with a session.
cookies, and most have a setting by which you can Call getAttribute(), cast the return value to the
globally switch to URL rewriting. appropriate type, and check whether the result is null.
 Either way, the servlet author doesnt need to bother 3. Storing information in a session. Use setAttribute()
with a key and a value.
with implementation details, doesnt have to explicitly
manipulate cookies or information appended to the URL, 4. Discarding session data. Call removeAttribute() to
discard a specific value. Call invalidate() to discard an
and is automatically given a convenient place to store
entire session. Call logout() to log the client out of the Web
arbitrary objects that are associated with each session.
server and invalidate all sessions associated with that user.

HTTPSession Example
Look up Session Info // Servlet that uses session tracking to keep per-client access counts.
import java.io.*;
import javax.servlet.*;
HttpSession session = request.getSession();
import javax.servlet.http.*;
ShoppingCart sc = (ShoppingCart) import java.util.*;
session.getAttribute("shoppingCart");
if (cart == null) { public class ShowSession extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
cart = new ShoppingCart();
throws ServletException, IOException {
session.setAttribute("shoppingCart", response.setContentType("text/html");
cart); HttpSession session = request.getSession();
} String heading;
... Integer accessCount = (Integer) session.getAttribute("accessCount");
if (accessCount == null) {
// do something with your shopping cart accessCount = new Integer(0);
object heading = "Welcome, Newcomer";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
HTTPSession Example
Figure: First visit by client
to ShowSession servlet.
session.setAttribute("accessCount", accessCount);
PrintWriter out = response.getWriter();
String title = "Session Tracking Example";
out.println("<HTML> );
out.println(..+session.getId());
out.println(..+session.getCreationTime());
out.println(..+session.getLastAccessedTime());
out.println(No. of page hit+accessCount);
}
}
Figure Twelfth visit to
ShowSession servlet. Access
count for this client is
independent of number of
visits by other clients.

HttpSession Methods ServletConfig (interface)


 public String getId()  When the servlet first starts up, the system can
 public Object getAttribute(String name) pass specific initialization information to the servlet
 public Enumeration getAttributeNames() for possible processing via the init()method.
 public long getCreationTime()
 public long getLastAccessedTime()  Parameters are passed in using a key/value pairing,
 public int getMaxInactiveInterval() and two methods are provided to access this data:
 public void setMaxInactiveInterval(int secs) getInitParameter()
 public void setAttribute(String name, Object value)
getInitParameterName()
 public boolean isNew()
 public void removeAttribute(String name)
 public void invalidate()
 public void logout()
ServletContext
ServletContext (interface)

 The ServletContext interface defines a set of


methods that can be used to communicate with the
server in a non-request-specific manner.
 This includes:
finding path information
accessing other servlets running on the server, and
writing to the server log file.
 Different virtual servers may return different servlet
contexts.

RequestDispatcher Status Codes


 Can forward request to another servlet response.sendError()
 Can include bits of content from other servlets in its  HttpServletResponse.SC_NOT_FOUND, Could not
own response find it);
 SC_OK = 200 // the success code
 RequestDispatcher d =
 SC_NO_CONTENT = 204 //content unchanged -- browser view
req.getRequestDispatcher(/servlet/OtherServlet) stays at the form but avoids contains no data error message
;  SC_MOVED_PERMANENTLY = 301
Either include() goes and comes back // browser uses Location header
d.include(req, resp);  SC_MOVED_TEMPORARILY = 302
// browser uses Location header
Or forward() doesnt come back  SC_UNAUTHORIZED = 401 // wrong authentication
d.forward(req, resp);  SC_NOT_FOUND = 404 // page not found
 Request dispatching is different from sendRedirect()  SC_INTERNAL_SERVER_ERROR = 500
 SC_NOT_IMPLEMENTED = 501 // for HEADER, PUT, DELETE
browser not involved  SC_SERVICE_UNAVAILABLE = 503
from user perspective, URL is unchanged
Example: Viewing the Currently Loaded Servlets
Interservlet Communication
public class Loaded extends HttpServlet {
 Servlets running together in the same server have public void doGet(HttpServletRequest req, HttpServletResponse res)
several ways to communicate with each other. throws ServletException, IOException {
res.setContentType("text/plain");
 A servlet obtains information about other servlets PrintWriter out = res.getWriter();
through the ServletContext object. ServletContext context = getServletContext();
Enumeration names = context.getServletNames();
 Use getServlet()to get a particular servlet.
while (names.hasMoreElements()) {
 You can also get all of the servlets using String name = (String)names.nextElement();
getServlets()[Deprecated in favour of Servlet servlet = context.getServlet(name);
out.println("Servlet name: " + name);
getServletNames()]
out.println("Servlet class: " + servlet.getClass().getName());
out.println("Servlet info: " + servlet.getServletInfo());
public Servlet ServletContext.getServlet(String name) throws ServletException out.println();
}
public Enumeration ServletContext.getServlets()
}}
public Enumeration ServletContext.getServletNames()

Example of Servlet Collaboration using Shared Object


Interservlet Communication: Servlet Collaboration

 Sometimes servlets have to cooperate, usually by


sharing some information.

Ref. Java Servlet Programming, OReilly


 Collaborating servlets can pass the shared
information directly from one servlet to another.
 Servlet collaboration can be achieved using shared
object (Object of singleton class)
Ref. Java Servlet Programming, OReilly
Example of Servlet Collaboration using Shared Object Example of Servlet Collaboration using Shared Object

Ref. Java Servlet Programming, OReilly


Example of Servlet Collaboration using Shared Object Example of Servlet Collaboration using Shared Object
Example 11-9. Consuming ingredients from the shared inventory
Ref. Java Servlet Programming, OReilly

Ref. Java Servlet Programming, OReilly

You might also like