Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
What is a Servlet?
A Servlet is a Java program that extends the
capabilities of servers.
Inherently multi-threaded.
Each request launches a new thread.
Input from client is automatically parsed into a
Request variable.
A servlet can be thought of as a server-side applet
Applet: a java program that runs within the web browser
Servlet: a java program that runs within the web server
Servlets are loaded and executed by a web server in the
same manner that applets are loaded and executed by a
web browser
CSIE33000 Network Programming Servelets 2
Shiow-yang Wu Note 1
CSIE33000 Net Programming Lecture11 Java Servelet
Server-Side Application
Architecture
Applications
Dynamic generates HTML pages
Access to database and/or back-end servers
etc.
CSIE33000 Network Programming Servelets 3
Weakness
CGI program may not be easily
portable to other platform
Substantial overhead is incurred
in starting the CGI process
CSIE33000 Network Programming Servelets 4
Shiow-yang Wu Note 2
CSIE33000 Net Programming Lecture11 Java Servelet
Servlet Architecture
HTTP request
Client Web Servlet
(web browser) Server Containter Servlet
HTTP response
Shiow-yang Wu Note 3
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 4
CSIE33000 Net Programming Lecture11 Java Servelet
Client Servlet-
Form:Client Enabled:Server
Lookup Static Page or
Launch Process/Thread
Http Request to Create Output
Lookup
Launch
Http Response Thread for
Client
Launch separate
Http thread to service
Response each request.
Shiow-yang Wu Note 5
CSIE33000 Net Programming Lecture11 Java Servelet
Writing Servlets
Install a web server capable of launching and
managing servlet programs.
Install the javax.servlet package to enable
programmers to write servlets.
Ensure CLASSPATH is changed to correctly
reference the javax.servlet package.
Define a servlet by subclassing the HttpServlet
class and adding any necessary code to the doGet()
and/or doPost() and if necessary the init()
functions.
Handler Functions
Each HTTP Request type has a separate handler
function.
GET -> doGet(HttpServletRequest, HttpServletResponse)
POST -> doPost(HttpServletRequest, HttpServletResponse)
PUT -> doPut (HttpServletRequest, HttpServletResponse)
DELETE -> doDelete (HttpServletRequest, HttpServletResponse)
TRACE -> doTrace (HttpServletRequest, HttpServletResponse)
OPTIONS -> doOptions (HttpServletRequest, HttpServletResponse)
Shiow-yang Wu Note 6
CSIE33000 Net Programming Lecture11 Java Servelet
A Servlet Template
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Important Steps
Import the Servlet API:
import javax.servlet.*;
import javax.servlet.http.*;
Extend the HTTPServlet class
Full servlet API available at:
http://www.java.sun.com/products/servlet/
Shiow-yang Wu Note 7
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 8
CSIE33000 Net Programming Lecture11 Java Servelet
Running Servlets
Jakarta/Apache Tomcat
Supercedes Java Apache and JServ
Macromedia JRun
ServletExec
Weblogic
Borland Enterprise Application
Server/JBuilder
Java Servlet Development Kit (JSDK)
Shiow-yang Wu Note 9
CSIE33000 Net Programming Lecture11 Java Servelet
Environment Access in
HTTPServletRequest
getContentLength() getServletPath()
getContentType() getPathInfo()
getProtocol() getPathTranslated()
getServerName() getQueryString()
getServerPort() getRemoteUser()
getRemoteAddr() getAuthType()
getRemoteHost() getHeader(“HdrStr”)
getMethod()
Shiow-yang Wu Note 10
CSIE33000 Net Programming Lecture11 Java Servelet
Parameter Access in
HTTPServletRequest
GetScheme GetHeader
GetInputStream getIntHeader, getDateHeader
GetParameter GetSession
GetParameterValues GetRequestedSessionId
GetParameterNames IsRequestedSessionIdValid
GetReader isRequestedSessionIDFromCookie
GetCharacterEncoding IsRequestedSessionIDFromUrl
GetContentType GetHeaderNames
GetCookies
GetRequestURI
GetHeaderNames
CSIE33000 Network Programming Servelets 21
HTTPResponse Methods
GetOutputStream SendError
GetWriter SendRedirect
GetCharacterEncoding SetHeader
SetContentLength setIntHeader,
SetContentType setDateHeader
SetStatus
AddCookie
encodeURL,
ContainsHeader
encodeRedirectURL
Shiow-yang Wu Note 11
CSIE33000 Net Programming Lecture11 Java Servelet
getParameter()
Use getParameter() to retrieve parameters from a
form by name.
Named Field values HTML FORM
<INPUT TYPE="TEXT" NAME="diameter">
In a Servlet
String sdiam = request.getParameter("diameter");
getParameter() cont’d
getParameter() can return three things:
String: corresponds to the parameter.
provided.
null: Parameter does not exist.
Shiow-yang Wu Note 12
CSIE33000 Net Programming Lecture11 Java Servelet
getParameterValues()
Used to retrieve multiple form parameters with the
same name.
For example, a series of checkboxes all have the
same name, and you want to determine which ones
have been selected.
Returns an array of Strings.
getParameterNames()
Returns an Enumeration object.
By cycling through the enumeration object, you can
obtain the names of all parameters submitted to
the servlet.
Note that the Servlet API does not specify the order
in which parameter names appear.
Shiow-yang Wu Note 13
CSIE33000 Net Programming Lecture11 Java Servelet
Circle Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class circle extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
Specify HTML
throws ServletException, IOException { output.
response.setContentType("text/html");
Attach a
PrintWriter out = response.getWriter(); PrintWriter to
Response Object
Circle Servlet
out.println("<BODY><H1 ALIGN=CENTER> Circle Info
</H1>\n");
try{
String sdiam = request.getParameter("diameter");
double diam = Double.parseDouble(sdiam);
out.println("<BR><H3>Diam:</H3>" + diam +
"<BR><H3>Area:</H3>" +
diam/2.0 * diam/2.0 * 3.14159 +
"<BR><H3>Perimeter:</H3>" +
2.0 * diam/2.0 * 3.14159);
} catch ( NumberFormatException e ){
out.println("Please enter a valid number");
}
out.println("</BODY></HTML>");
}
Shiow-yang Wu Note 14
CSIE33000 Net Programming Lecture11 Java Servelet
Session Tracking
Many applications need to maintain state across a series
of requests from the same user (or originating from the
same browser), e.g.,
When clients at an on-line store add an item to their
Shiow-yang Wu Note 15
CSIE33000 Net Programming Lecture11 Java Servelet
What is Cookie
Cookie is a small amount of information sent
by a servlet to a web browser
Saved by the browser, and later sent back to
the server in subsequent requests
A cookie has a name, a single value, and
optional attributes (name/value pair)
A cookie’s value can uniquely identify a client
Server uses cookie’s value to extract
information about the session from some
location on the server
CSIE33000 Network Programming Servelets 31
Shiow-yang Wu Note 16
CSIE33000 Net Programming Lecture11 Java Servelet
Cookie Servlet
public class CookieTest extends HttpServlet {
public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException {
OutputStream out = res.getOutputStream();
PrintWriter pw = new PrintWriter(new BufferedWriter(new
OutputStreamWriter(out)));
Cookie[] cookies = req.getCookies();
Cookie current = null;
if (cookies != null) {
for (int i=0; i < cookies.length; i++) {
pw.println("name=“ + cookies[i].getName());
pw.println("value=“ + cookies[i].getValue());
pw.println("version=“ + cookies[i].getVersion());
if (cookies[i].getName().equals("cookie"))
{ current=cookies[i]; }
pw.println();
} }
CSIE33000 Network Programming Servelets 34
Shiow-yang Wu Note 17
CSIE33000 Net Programming Lecture11 Java Servelet
Cookie Servlet
int count=0;
if (current != null) {
count = Integer.parseInt(current.getValue());
res.addCookie(new Cookie("previouscookie",
new Integer(count).toString()));
count++;
}
pw.println("Value stored in cookie = "+count);
pw.flush();
pw.close();
count++;
res.addCookie(new Cookie("cookie",
new Integer(count).toString()));
} }
CSIE33000 Network Programming Servelets 35
Shiow-yang Wu Note 18
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 19
CSIE33000 Net Programming Lecture11 Java Servelet
URL Rewriting
URLs can be rewritten or encoded to include
session information
URL rewriting usually includes a session ID
Session ID can be sent as an added
parameters:
http://.../servlet /Rewritten?sessionid=678
Shiow-yang Wu Note 20
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 21
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 22
CSIE33000 Net Programming Lecture11 Java Servelet
HttpSession
To get a user’s existing or new session object:
HttpSession session = request.getSession(true)
flag = true to create a new session if none exists
HttpSession is a java interface containing methods to
View and manipulate information about a session, such as the session
identifier, creation time, and last accessed time
Bind objects to sessions, allowing user information to persist across
multiple user connections
To Store and retrieve of attribute
session.setAttribute(“cartItem”, cart)
session.getAttribute(“cartItem”)
All session data are kept on the server
Only session ID sent to client
CSIE33000 Network Programming Servelets 45
Shiow-yang Wu Note 23
CSIE33000 Net Programming Lecture11 Java Servelet
Session Timeout
Used when an end-user can leave the
browser without actively closing a session
Session usually timeout after 30 minutes of
inactivity
Product specific
A different timeout may be set
getMaxInactiveInterval()
setMaxInactiveInterval()
Shiow-yang Wu Note 24
CSIE33000 Net Programming Lecture11 Java Servelet
Session Invalidation
Can be used by servlet programmer to end a
session proactively by calling invalidate()
When a user at the browser clicks on “logout”
button
When business logic ends a session
Caution: a session object could be shared by
multiple servlet/JSP-pages and invalidating it
could destroy data that other servlet/JSP-
pages are using
Shiow-yang Wu Note 25
CSIE33000 Net Programming Lecture11 Java Servelet
HttpSession Methods
Object getAttribute(String) – Value for the given
name
Enumeration getAttributeNames() - All the
names of all attributes in the session
long getCreationTime() - Time at which this
session was created
String getId() - Identifier assigned to this session
long getLastAccessedTime() - Last time the client
sent a request carrying the identifier assigned to the
session
int getMaxInactiveInterval() - Max time (in
seconds) between requests that the session will be
kept
CSIE33000 Network Programming Servelets 51
HttpSession Methods
ServletContext getServletContext() -
ServletContext for session
void invalidate() - Invalidates the session
boolean isNew() - true if it has been created by
the server (client has not yet acknowledged joining
the session)
void setAttribute(String, Object) - Sets the
value for the given name
void removeAttribute(String) - Removes the
value for the given name
void setMaxInactiveInterval(int) - Sets the
maximum interval between requests
Shiow-yang Wu Note 26
CSIE33000 Net Programming Lecture11 Java Servelet
Assignment 6
A simple e-commerce site
To understand how server-side applications are
designed
To practice how to implement server-side
applications using Java servlet
To practice the handling of Web sessions
Shiow-yang Wu Note 27