servelets ppt
TRANSCRIPT
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 1
Lecture 15: Servelets
Based on Notes by Dave Hollinger & Ethan Cerami
Also, the Online Java Tutorial by Sun
CSIE33000 Network Programming Servelets 2
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 browserServlet: a java program that runs within the web serverServlets are loaded and executed by a web server in the same manner that applets are loaded and executed by a web browser
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 2
CSIE33000 Network Programming Servelets 3
Server-Side ApplicationArchitecture
ApplicationsDynamic generates HTML pagesAccess to database and/or back-end serversetc.
CSIE33000 Network Programming Servelets 4
Server-Side Application: CGIsCommon Gateway Interface (CGI)
Basically call external programUse standard input and output for data exchangeProgramming language independent
WeaknessCGI program may not be easily portable to other platformSubstantial overhead is incurred in starting the CGI process
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 3
CSIE33000 Network Programming Servelets 5
Servlet Architecture
The client makes a request via HTTPThe web server receives the requests and forwards it to the servlet
If the servlet has not yet been loaded, the web server loads it into the JVM and executes it
The servlet receives the HTTP request and performs some type of processThe servlet returns a response to the web serverThe web server forwards the response to the client
Client (web browser)
WebServer
HTTP request
HTTP response
ServletContainter Servlet
CSIE33000 Network Programming Servelets 6
Why Use Servlets
Servlets are designed to replace CGI scriptsPlatform-independent and extensible
CGI scripts are typically written in Perl or C, and are very much tied to a particular server platformServlet is written in Java, which can easily integrate with existing legacy systems through RMI, CORBA, and/or JNI
Persistent and fastServers are loaded only once by the web server and can maintain services between requests (particularly important for maintaining database connections) CGI scripts are transient – a CGI script is removed from memory after it is completeFor each browser request, the web server must spawn a new operating system process
SecureThe only way to invoke a servlet from the outside world is through a web server, which can be protected behind a firewall
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 4
CSIE33000 Network Programming Servelets 7
What can you build with servlets
Search enginesE-commerce applicationsShopping cartsProduct catalogsPersonalization systemsIntranet application Groupware applications: bulletin boards, file sharing, etc.
CSIE33000 Network Programming Servelets 8
Steps of Servlet Processing1. Read any data sent by the server
Capture data submitted by an HTML form2. Look up any HTTP information
Determine the browser version, host name of client, cookies, etc.
3. Generate the resultsConnect to databases, connect to legacy applications, etc.
4. Format the resultsGenerate HTML on the fly
5. Set the appropriate HTTP headersTell the browser the type of document being returned or set any cookies
6. Send the document back to the client
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 5
CSIE33000 Network Programming Servelets 9
Servlet Life CycleCreate (Servlet Instantiation):
Loading the servlet class and creating a new instanceInitialize (Servlet Initialization):
Initialize the servlet using the init() methodService (Servlet processing):
Handling 0 or more client requests using the service()method
Destroy (Servlet Death): Destroying the servlet using the destroy() method
When HTTP calls for a servletNot loaded: Load, Create, Init, ServiceAlready loaded: Service
CSIE33000 Network Programming Servelets 10
Servlet-Enabled:Server
Client Form:Client
Http Response
Lookup Static Page or Launch Process/Thread to Create Output
On first access launch the servletprogram.
Launch separate thread to service each request.
Launch Thread for Client
Launch Servlet
Http RequestLookup
Http Response
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 6
CSIE33000 Network Programming Servelets 11
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 HttpServletclass and adding any necessary code to the doGet()and/or doPost() and if necessary the init()functions.
CSIE33000 Network Programming Servelets 12
Handler FunctionsEach 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)
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 7
CSIE33000 Network Programming Servelets 13
A Servlet Templateimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;
public class ServletTemplate extends HttpServlet {public void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
// Use "request" to read incoming HTTP headers// (e.g. cookies) and HTML form data (e.g. data the user// entered and submitted).
// Use "response" to specify the HTTP response status// code and headers (e.g. the content type, cookies).
PrintWriter out = response.getWriter();// Use "out" to send content to browser
}}
CSIE33000 Network Programming Servelets 14
Important Steps
Import the Servlet API:import javax.servlet.*;import javax.servlet.http.*;
Extend the HTTPServlet classFull servlet API available at:
http://www.java.sun.com/products/servlet/
You need to overrride at least one of the request handlers!Get an output stream to send the response back to the client
All output is channeled to the browser.
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 8
CSIE33000 Network Programming Servelets 15
doGet and doPost
The handler methods each take two parameters:HTTPServletRequest: encapsulates all information regarding the browser request.
Form data, client host name, HTTP request headers.
HTTPServletResponse: encapsulate all information regarding the servlet response.
HTTP Return status, outgoing cookies, HTML response.
If you want the same servlet to handle both GET and POST, you can have doGet call doPost or vice versa.
Public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
{doPost(req,res);}
CSIE33000 Network Programming Servelets 16
Hello World Servletimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWWW extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponseresponse) throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("<HTML>\n" +
"<HEAD><TITLE>Hello WWW</TITLE></HEAD>\n" +"<BODY>\n" +"<H1>Hello WWW</H1>\n" +"</BODY></HTML>");
}}
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 9
CSIE33000 Network Programming Servelets 17
Running Servlets
Jakarta/Apache TomcatSupercedes Java Apache and JServ
Macromedia JRunServletExecWeblogicBorland Enterprise Application Server/JBuilderJava Servlet Development Kit (JSDK)
CSIE33000 Network Programming Servelets 18
Single Threaded Example
By default, uses shared threadsSingle instance of servlet shared by all requestsOne thread created for each requestClass & instance variables are thread-unsafe; auto variables are thread-safe
In some applications, you have to use single thread model, which
Results in new servlet for each requestAllows use of instance variables w/o synchronization
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 10
CSIE33000 Network Programming Servelets 19
Single Threaded Exampleimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorld extends HttpServlet
implements javax.servlet.SingleThreadModel{public void doGet(HttpServletRequest req,
HttpServletResponse res) throws IOException{// Code here!
}}
CSIE33000 Network Programming Servelets 20
Environment Access in HTTPServletRequest
getContentLength()getContentType()getProtocol()getServerName()getServerPort()getRemoteAddr()getRemoteHost()getMethod()
getServletPath()getPathInfo()getPathTranslated()getQueryString()getRemoteUser()getAuthType()getHeader(“HdrStr”)
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 11
CSIE33000 Network Programming Servelets 21
Parameter Access in HTTPServletRequest
GetSchemeGetInputStreamGetParameterGetParameterValuesGetParameterNamesGetReaderGetCharacterEncodingGetContentTypeGetCookiesGetRequestURIGetHeaderNames
GetHeadergetIntHeader, getDateHeaderGetSessionGetRequestedSessionIdIsRequestedSessionIdValidisRequestedSessionIDFromCookieIsRequestedSessionIDFromUrlGetHeaderNames
CSIE33000 Network Programming Servelets 22
HTTPResponse Methods
GetOutputStreamGetWriterGetCharacterEncodingSetContentLengthSetContentTypeAddCookieContainsHeader
SendErrorSendRedirectSetHeadersetIntHeader, setDateHeaderSetStatusencodeURL, encodeRedirectURL
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 12
CSIE33000 Network Programming Servelets 23
getParameter()Use getParameter() to retrieve parameters from a form by name.
<INPUT TYPE="TEXT" NAME="diameter">
String sdiam = request.getParameter("diameter");
Named Field values HTML FORM
In a Servlet
CSIE33000 Network Programming Servelets 24
getParameter() cont’dgetParameter() can return three things:
String: corresponds to the parameter.Empty String: parameter exists, but no value provided.null: Parameter does not exist.
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 13
CSIE33000 Network Programming Servelets 25
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.
CSIE33000 Network Programming Servelets 26
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.
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 14
CSIE33000 Network Programming Servelets 27
Circle Servletimport java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class circle extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter(); Attach a PrintWriter to Response Object
Specify HTML output.
CSIE33000 Network Programming Servelets 28
Circle Servletout.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>");
}
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 15
CSIE33000 Network Programming Servelets 29
Session TrackingMany 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 shopping cart, how does the server know what’s already in the cart?When clients decide to proceed to checkout, how can the server determine which previously created shopping cart is theirs?
HTTP is a stateless protocolEach time, a client talks to a web server, it opens a new connectionServer does not automatically maintains “conversational state” of a user
CSIE33000 Network Programming Servelets 30
Session Tracking Mechanisms
Three mechanisms of session trackingCookiesURL rewritingHidden form fields
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 16
CSIE33000 Network Programming Servelets 31
What is CookieCookie is a small amount of information sent by a servlet to a web browserSaved 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 32
Cookies and ServletsThe HttpServletRequest class includes the “getCookies()” function.
This returns an array of cookies, or null if there aren’t any.
Cookies can then be accessed using three methods.
String getName()String getValue()String getVersion()
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 17
CSIE33000 Network Programming Servelets 33
Cookies & Servlets cont’dCookies can be created using HttpServletResponse.addCookie() and the constructor
new Cookie(String name, String value);Expiration can be set using
setMaxAge(int seconds)
CSIE33000 Network Programming Servelets 34
Cookie Servletpublic 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 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 18
CSIE33000 Network Programming Servelets 35
Cookie Servletint 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 36
Cookies as Session Tracking Mechanism
AdvantageVery easy to implementHighly customablePersist across browser shut-downs
Disadvantage Users may turn off cookies for privacy or security reasonNot quite universal browser support
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 19
CSIE33000 Network Programming Servelets 37
Sessions & ServletsServlets also support simple transparent sessions
Interface HttpSessionGet one by using HttpServletRequest.getSession()
You can store & retrieve values in the sessionputValue(String name, String value)String getValue(String name)String[] getNames()
CSIE33000 Network Programming Servelets 38
Sessions & Servlets cont’dVarious other information is stored
long getCreationTime()String getId()long getLastAccessedTime()
Also can set timeout before session destruction
int getMaxInactiveInterval()setMaxInactiveInterval(int seconds)
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 20
CSIE33000 Network Programming Servelets 39
URL RewritingURLs can be rewritten or encoded to include session informationURL rewriting usually includes a session IDSession ID can be sent as an added parameters:
http://.../servlet /Rewritten?sessionid=678
CSIE33000 Network Programming Servelets 40
URL Rewriting as Session Tracking
AdvantagesUsers remain anonymousThere are universal support
DisadvantagesTedious to rewrite all URLsOnly works for dynamically created documents
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 21
CSIE33000 Network Programming Servelets 41
Hidden Form FieldsHidden form fields do not display in the browser, but can be sent back to the server by submit<INPUT TYPE=“HIDDEN” Name=“session” Value =‘…’>
Fields can have identification (session id) or just something to rememberServlet reads the fields using request.getParameter()
CSIE33000 Network Programming Servelets 42
Hidden Form Fields as Session Tracking
AdvantagesUniversally supportedAllow anonymous users
DisadvantagesOnly works for a sequence of dynamically generated formsBreaks down with static documents, emailed documents, bookmarked documentsCannot support browser shutdown
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 22
CSIE33000 Network Programming Servelets 43
Steps of Doing Session Tracking Programmers have to do the following steps in order to use the aforementioned tracking mechanisms:
Generating and maintaining a session id for each sessionPassing session id to client via either cookie or URLExtracting session id either from cookie or URLCreating and maintaining a hashtable in which session id and session information are storedComing up with a scheme in which session information can be added or removed
These mechanisms can pass “session id”, butdo not provide high-level programming APIsdo not provide a framework from managing sessions
CSIE33000 Network Programming Servelets 44
“Session Tracking” Features of Servlet
Provides higher-level API for session trackingBuilt on top of cookie or URL rewriting
Servlet container maintainsInternal hashtable of session idsSession information in the form of HttpSessionProvides a simple API for adding and removing session information (attributes) to HttpSessionCould automatically switch to URL rewriting if cookies are unsupported or explicitly disabled
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 23
CSIE33000 Network Programming Servelets 45
HttpSessionTo 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 toView and manipulate information about a session, such as the session identifier, creation time, and last accessed timeBind objects to sessions, allowing user information to persist across multiple user connections
To Store and retrieve of attributesession.setAttribute(“cartItem”, cart)session.getAttribute(“cartItem”)
All session data are kept on the serverOnly session ID sent to client
CSIE33000 Network Programming Servelets 46
Sample HTTP Sessionpublic class SessionServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws IOException {res.setContentType("text/html");OutputStream out = res.getOutputStream();PrintWriter pw = new PrintWriter(new
OutputStreamWriter(out));HttpSession session = req.getSession(false);if (session == null) {
session=req.getSession(true);session.putValue("VisitCount", "1");
}pw.println("<html><body><pre>");pw.println("session.isNew()=“ + session.isNew());
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 24
CSIE33000 Network Programming Servelets 47
Sample HTTP Sessionpw.println("session.getCreationTime()=“ + new
java.util.Date(session.getCreationTime()));pw.println("session.getID()=“ + session.getId());pw.println("session.getLastAccessedTime()=" + new
java.util.Date(session.getLastAccessedTime()));String strCount =(String)
session.getValue("VisitCount");pw.println("No. of times visited = " + strCount);int count = Integer.parseInt(strCount); count++;session.putValue("VisitCount",
Integer.toString(count));pw.println ("</pre></body></html>");pw.flush();
}}
CSIE33000 Network Programming Servelets 48
Session TimeoutUsed when an end-user can leave the browser without actively closing a sessionSession usually timeout after 30 minutes of inactivity
Product specificA different timeout may be set
getMaxInactiveInterval()setMaxInactiveInterval()
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 25
CSIE33000 Network Programming Servelets 49
Issues with “Stale” Session Objects
The number of “stale” session objects that are in “to be timed out” could be large and affect system performance, for example,
1000 users with average 2 minutes session time, thus 15000 users during a period of 30 minutes4K bytes of data per session15000 sessions * 4K = 60M bytes of session data – just for one application
CSIE33000 Network Programming Servelets 50
Session InvalidationCan be used by servlet programmer to end a session proactively by calling invalidate()
When a user at the browser clicks on “logout”buttonWhen 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
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 26
CSIE33000 Network Programming Servelets 51
HttpSession Methods
Object getAttribute(String) – Value for the given nameEnumeration getAttributeNames() - All the names of all attributes in the sessionlong getCreationTime() - Time at which this session was createdString getId() - Identifier assigned to this sessionlong getLastAccessedTime() - Last time the client sent a request carrying the identifier assigned to the sessionint getMaxInactiveInterval() - Max time (in seconds) between requests that the session will be kept
CSIE33000 Network Programming Servelets 52
HttpSession MethodsServletContext getServletContext() -ServletContext for sessionvoid invalidate() - Invalidates the sessionboolean 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 namevoid removeAttribute(String) - Removes the value for the given namevoid setMaxInactiveInterval(int) - Sets the maximum interval between requests
CSIE33000 Net Programming Lecture11 Java Servelet
Shiow-yang Wu Note 27
CSIE33000 Network Programming Servelets 53
Assignment 6A simple e-commerce site
To understand how server-side applications are designedTo practice how to implement server-side applications using Java servletTo practice the handling of Web sessions
Due: May 27, 2004