Documentos de Académico
Documentos de Profesional
Documentos de Cultura
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
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
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
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
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 {
29 30
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
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
</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
*/
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(); */
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
}
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
53 54
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
59
Session Tracking Session Tracking
Request
Session ID = 123XYZ Session ID = 123XYZ
Response:
Set-Cookie: sid=123XYZ
Servlet Container Servlet Container
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]
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.
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.