370 likes | 509 Views
Web Computing: Servlet CS587x Lecture 10 Department of Computer Science Iowa State University. What to cover. Introduction to Servlet Servlet architecture Servlet programming and example Session management Cookie URL rewriting Hidden form field HttpSession. What is a Servlet.
E N D
Web Computing: Servlet CS587x Lecture 10 Department of Computer Science Iowa State University
What to cover • Introduction to Servlet • Servlet architecture • Servlet programming and example • Session management • Cookie • URL rewriting • Hidden form field • HttpSession
What is a Servlet • 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
The Job of Servlet • Read the explicit data sent by the client • Capture data submitted by an HTML form or an applet • Read the implicit HTTP request data sent by the browser • browser version, host name of client, cookies, etc. • Generate the results • Connect to databases/legacy applications, execute an RMI or CORBA call etc. • Format the response data • Explicit data (Generate HTML on the fly) • Implicit data (e.g. HTTP header, etc.) • Send the document back to the client
Why Use Servlets • Platform-independent and extensible • CGI scripts are typically written in Perl or C, and are very much tied to a particular server platform • Servlet is written in Java, which can easily integrate with existing legacy systems through RMI, CORBA, and/or JNI • Persistent and Efficient • Servers 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 complete • For each browser request, the web server must spawn a new operating system process • Convenient • Servlet can automatically parse and decode HTML form data, reading and setting HTTP headers, handling cookies, tracking sessions, and many other such high-level utilities. • Secure • CGI are often executed by general-purpose operating system shells and must be careful to filter out characters such as backquotes and semicolons that are treated specially by the shell
What can you build with servlets • Search engines • E-commerce applications • Shopping carts • Product catalogs • Personalization systems • Intranet application • Groupware applications: bulletin boards, file sharing, etc.
Servlet Architecture • The client makes a request via HTTP • The 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 process • The servlet returns a response to the web server • The web server forwards the response to the client Web Server Servlet Containter Client (web browser) HTTP request Servlet HTTP response
Steps of Servlet Processing • Read any data sent by the server • Capture data submitted by an HTML form • Look up any HTTP information • Determine the browser version, host name of client, cookies, etc. • Generate the results • Connect to databases, connect to legacy applications, etc. • Format the results • Generate HTML on the fly • Set the appropriate HTTP headers • Tell the browser the type of document being returned or set any cookies • Send the document back to the client
Servlet Life Cycle • Servlet life cycle • Create • Initialize • Service • Destroy • When HTTP calls for a servlet • Not loaded: Load, Create, Init, Service • Already loaded: Service
How to program servlets • Servlets rely on classes defined in the javax.servlet and javax.servlet.http packages • The two packages are standard extension to Java API • A user servlet implements the servlet interface, which provides • the basic structure methods for servlets, such as initializing, service, and destruction methods • The methods for accessing context & configuration • HTTPServlet class • Starting point for new web servlets • Extend the class & override desired methods: • doGet, doPost, doPut, doDelete, doTrace, and doOptions • Called by the HTTPServlet's service method based on HTTP request • Each returns HTTP_BAD_REQUEST error response
HTTP Commands Servlet Methods • doGet • doHead • doPut • doDelete • doPost • GET • Transfer resource from given URL • HEAD • Get resource metadata (headers) only • PUT • Store/modify resource under a given URL • DELETE • Remove resource • POST • Provide input for a process identified by the given URL (usually used to post CGI parameters)
Get & Post Similarities • GET and POST methods look the same to servlets • Can override doGet and doPost like this to perform common operations: public void doGet(HttpServletRequest req, HttpServletResponse res) { doGetPost(req, res); } public void doPut(HttpServletRequest req, HttpServletResponse res) { doGetPost(req, res); } public void doGetPut(HttpServletRequest req, HttpServletResponse res) { // Implement the common code here }
Simple Servlet import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends javax.servlet.http.HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { res.setContentType("text/html"); OutputStream out = res.getOutputStream(); PrintWriter pw = new PrintWriter(new BufferedWriter(new OutputStreamWriter(out))); pw.println ("<CENTER><H3> Hello World </H3></CENTER>"); pw.flush(); pw.close(); } }
Running Servlets • Jakarta/Apache Tomcat • Supercedes Java Apache and JServ • Macromedia JRun • ServletExec • Weblogic • Borland Enterprise Application Server/JBuilder • Java Servlet Development Kit (JSDK)
Single Threaded Example • By default, uses shared threads • Single instance of servlet shared by all requests • One thread created for each request • Class & instance variables are thread-unsafe; auto variables are thread-safe • In some applications, you have to use multiple thread model, which • Results in new servlet for each request • Allows use of instance variables w/o synchronization public class HelloWorld extends javax.servlet.http.HttpServlet implements javax.servlet.SingleThreadModel { public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException { // Code here! } }
Environment Access in HTTPServletRequest • getContentLength() • getContentType() • getProtocol() • getServerName() • getServerPort() • getRemoteAddr() • getRemoteHost() • getMethod() • getServletPath() • getPathInfo() • getPathTranslated() • getQueryString() • getRemoteUser() • getAuthType() • getHeader(“HdrStr”)
Parameter Access in HTTPServletRequest • GetScheme • GetInputStream • GetParameter • GetParameterValues • GetParameterNames • GetReader • GetCharacterEncoding • GetContentType • GetCookies • GetRequestURI • GetHeaderNames • GetHeader • getIntHeader, getDateHeader • GetSession • GetRequestedSessionId • IsRequestedSessionIdValid • isRequestedSessionIDFromCookie • IsRequestedSessionIDFromUrl • GetHeaderNames
HTTPResponse Methods • GetOutputStream • GetWriter • GetCharacterEncoding • SetContentLength • SetContentType • AddCookie • ContainsHeader • SendError • SendRedirect • SetHeader • setIntHeader, setDateHeader • SetStatus • encodeURL, encodeRedirectURL
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 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 protocol • Each time, a client talks to a web server, it opens a new connection • Server does not automatically maintains “conversational state” of a user
Session Tracking Mechanisms • Three mechanisms of session tracking • Cookies • URL rewriting • Hidden form fields
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
Cookie Servlet public class CookieTest extends javax.servlet.http.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(); } } 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())); } }
Cookies as Session Tracking Mechanism • Advantage • Very easy to implement • Highly customable • Persist across browser shut-downs • Disadvantage • Users may turn off cookies from privacy or security reason • Some browsers may not support
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
URL Rewriting as Session Tracking • Advantages • Users remain anonymous • There are universally supported • Disadvantages • Tedious to rewrite all URLs • Only works for dynamically created documents
Hidden Form Fields • Hidden 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 remember • Servlet reads the fields using request.getParameter()
Hidden Form Fields as Session Tracking • Advantages • Universally supported • Allow anonymous users • Disadvantages • Only works for a sequence of dynamically generated forms • Breaks down with static documents, emailed documents, bookmarked documents • Cannot support browser shutdown
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 session • Passing session id to client via either cookie or URL • Extracting session id information either from cookie or URL • Creating and maintaining a hashtable in which session id and session information are stored • Coming up with a scheme in which session information can be added or removed • These mechanisms can pass “session id”, but • do not provide high-level programming APIs • do not provide a framework from managing sessions
“Session Tracking” features of Servlet • Provides higher-level API for session tracking • Built on top of cookie or URL rewriting • Servlet container maintains • Internal hashtable of session ids • Session information in the form of HttpSession • Provides a simple API for adding and removing session information (attributes) to HttpSession • Could automatically switch to URL rewriting if cookies are unsupported or explicitly disabled
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 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
Sample HTTP Session public 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()); pw.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(); } }
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()
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 minutes • 4K bytes of data per session • 15000 sessions * 4K = 60M bytes of session data – just for one application
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
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 between requests that the session will be kept • 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