Servlets and JSP (Java Server Pages) XML HTTP CGI Web usability Last Week Nan Niu (nn@cs.toronto.edu) CSC309 -- Fall 2008 2 Servlets Generic Java2EE API for invoking and connecting to mini-servers (lightweight, short-lived, server-side interactions) Mostly HTTPServlets Generate HTTP responses (as for CGI) Embedded via <servlet> tag into HTML pages for server-side includes Servlet code snippets can be embedded directly into HTML pages: JSP = Java Server Pages Competitor: Microsoft ASP = Active Server Pages 3 Servlet Architecture Clients: browsers, e.g., IE, Netscape Web server: e.g., Apache, IIS CGI Protocol: Specifying what a request/response looks like Servlet container: Running JVM, hooked into the Web server, loads and maintains servlets, session info, object store Servlet: A Java class used to handle a specific request. 4 Servlet Interaction Client Makes a request by specifying a URL + additional info. Basically a method call, the method and arguments Web Server Receives the request Identifies the request as a servlet request Passes the request to the servlet container Servlet Container Locates the servlet (Java code, loaded and running in the container JVM) Feeds the request parameters to the servlet Servlet Executes in a separate thread The servlet can store/retrieve objects (possibly session scoped) from the servlet container Output is sent back to the requesting browser CGI1 CGI2 CGI1 CGI vs. Servlet CGI-Based Web Server Main Process Child Process for CGI1 Child Process for CGI2 Child Process for CGI1 Servlet continues to be available in the container 5 6 1
Setvlet2 CGI vs. Servlet Java Servlet-Based Web Server Main Process JVM Servlet2 7 Servlets vs. CGI Servlets Faster than CGI scripts because a different process model is used Also Java just-in-time compilation increases performance Process model allows resource sharing (e.g., database connection sharing) Container is always available Has all the advantages of Java programming language, including ease of development and platform independence Same language for both client- and server-side development Can access the large set of APIs for the Java platform Has access to CGI support through the servlet API Has session awareness, ability to store and retrieve scoped objects from servlet container 8 Servlet API (javax.servlet) Servlet Container Servlet Interface HttpServletRequest HttpServletResponse ServletContext Servlet Container Contains and manages servlets through their lifecycle Provides the network services over which requests and responses are sent Decodes requests Formats responses 9 10 Servlet Interface Central abstraction of the servlet API All servlets either implement this interface, or extend a class that implements this interface GenericServlet and HttpServlet are two classes in the servlet API that implement the Servlet interface User-defined Servlets Inherit from HttpServlet Override doget() and dopost() Have no main() method 11 12 2
doget() and dopost() protected void doget( HttpServletRequest req, HttpServletResponse resp) import java.io.*; import javax.servlet.*; import javax.servlet.http.*; Hello World public class HelloWorld extends HttpServlet { public void doget(httpservletrequest req, HttpServletResposse resp) throws ServletException, IOException { resp.setcontenttype( text/html ); PrintWriter out = resp.getwriter(); out.println( <html> ); out.println( <head><title>hello world</title></head> ); protected void dopost( HttpServletRequest req, HttpServletResponse resp) 13 out.println( <body><h2>hello World</h2></body> ); out.println( </html> ); public void dopost(httpservletrequest req, HttpServletResposse resp) throws ServletException, IOException { doget(req, resp); 14 Handling GET and POST Request Servlet API (javax.servlet) Servlet Container Servlet Interface HttpServletRequest HttpServletResponse ServletContext Servlet Lifecycle 15 16 Servlet Lifecycle Inherited from GenericServlet init() destroy() Defined by HttpServlet doget() dopost() Servlet Container Provide Web server with servlet support Execute and manage servlets, e.g., Tomcat Must conform to the following lifecycle contract Create and initialize the servlet Handle zero or more service calls from clients Destroy the servlet and then garbage collect it Three types Standalone container Add-on container Embeddable container Usually execute all servlets in a single JVM 17 18 3
Loading Servlet Server calls servlet s init() method After the server constructs the servlet instance and before the servlet handles any requests init() Servlet initialization is defined May be called When the server starts When the servlet is first requested, just before the service() method is invoked At the request of the server administrator Removing Servlet Server calls the destroy() method After the servlet has been taken out of service and all pending requests to the servlet have completed or timed out destroy() Resources acquired should be freed up A chance to write out its unsaved cached info. Last step before being garbage collected 19 20 Servlet Instance Persistence Servlets persist between requests as object instances When the servlet is loaded, the server creates a single instance The single instance handles every request made of the servlet Improves performance in three ways Keeps memory footprint small Eliminates the object creation overhead Enables persistence May have already loaded required resources Setvlet2 Servlet Model Java Servlet-Based Web Server Main Process JVM Servlet2 21 22 import java.io.*; import javax.servlet.*; import javax.servlet.http.*; A Simple Counter Multi-threading public class SimpleCounter extends HttpServlet { int count = 0; public void doget(httpservletrequest req, HttpServletResposse resp) throws ServletException, IOException { resp.setcontenttype( text/plain ); PrintWriter out = resp.getwriter(); count++; out.println( Since loading, this servlet has been accessed + count + times. ); 23 Each client request is another thread that calls the servlet via service(), doget(), and dopost() methods 24 4
Safety Non-local variables are not thread-safe Variables declared within a class but outside any specific method May cause data corruption and inconsistencies In the example: count++ //thread 1 count++ //thread 2 out.println //thread 1 out.println //thread 2 Local variables are thread-safe Variables declared within a method 25 Synchronization Place code within a synchronization block Guaranteed not to be executed concurrently by another thread Before any thread begins to execute synchronized code A monitor (lock) must be obtained on a specified object instance If one thread already has the monitor, all other threads must wait Use only when necessary Reduce parallelism Increased overhead to obtain the monitor 26 SimpleCounter Has Four Options Option 1 Don t care; can live with inconsistency Option 2 public synchronized void doget( ) Option 3 PrintWriter out = resp.getwriter(); synchronized(this) { count++; out.println( Since loading, this servlet has been accessed + count + times. ); Option 4 (the best) PrintWriter out = resp.getwriter(); int local_count; synchronized(this) { local_count = ++count; out.println( Since loading, this servlet has been accessed + local_count + times. ); 27 Servlet API (javax.servlet) Servlet Container Servlet Interface HttpServletRequest HttpServletResponse ServletContext Servlet Lifecycle 28 HttpServletRequest Encapsulate all information from the client request HTTP request header and request body Methods to retrieve data Inherited from ServletRequest getparameter() getparameternames() getparametervalues() getinputstream() getreader() HttpServletResponse Encapsulate all data to be returned to client HTTP response header and response body Set HTTP response header Primitive manipulation setstatus(), setheader(), addheader() Convenience methods setcontenttype(), sendredirect(), senderror() Set HTTP response body Obtain a PrintWriter or ServletOutputStream to return data to the client getwriter(), getoutputstream() 29 30 5
ServletContext Reference to the Web application in which servlets execute One ServletContext for each app. on the server Allow servlets to access server information ServletContext GenericServlet.getServletContext() Using ServletContext, servlets can Log events Obtain URL references to resources Access to initialization parameters (in web.xml) Share attributes with other servlets in the context Not thread safe 31 Session Management HTTP is stateless: No memory of browser s state Preserving state between browser and Web server interaction Probably determined by previous forms filled in and pages viewed Kept at the browser or/and at the Web server Example: User authentication: post questions only after the user is logged in Session recognition: don t want to require a user to log in at every page 32 Session Management (Cont d) At client Cookies Hidden variables URL rewriting At server Servlet s built-in session tracking Database, file system, etc. Cookies Stored at the browser As name=value pairs Browsers limit the size of cookies Users can refuse to accept them Attached to subsequent requests to the same server Servlets can create cookies Included in the HTTP response header 33 34 Cookie Cookie(String name, String value) setmaxage(int expiry) Adding a Cookie setdomain(string pattern) setpath(string uri) setsecure(boolean flag) HttpServletResponse addcookie(cookie cookie) Path MaxAge Given in seconds If negative, cookie persists until browser exists Domain Return cookie to servers matching the specified domain pattern By default, only return to the server that sent it Where the client should return the cookie Visible to all the pages in the specified (sub-)directory Secure flag Send cookies only on secure Retrieving Cookie Values HttpServletRequest public Cookies[] getcookies() Cookie getname() getvalue() getdomain() getpath() getsecure() channels 35 36 6
Hidden Variables Supported by all browsers Requires all hidden variables to appear in all forms <input type= hidden name= userid value= 309 /> State is sent inside each Web page For form-based applications only Following hyperlinks may cause a loss of state Current submitted page represents current state independent of what was done previously URL Rewriting Rewrite URLs so that they include state variables Each URL is now a CGI-get request Supported by all browsers Requires all URLs contain all state information (long URLs) Current submitted page represents current state independent of what was done previously 37 38 Servlet s Built-in Session Tracking Session tracking API Devoted to servlet session tracking Most servers support session tracking Through the use of cookies Able to revert to URL rewriting when cookies fail Servlet uses the token to fresh session state Session objects are maintained in memory Some servers allow them to be written to file system or database as memory fills up or when server shuts down Items in the session need to be serializable 39 Session Tracking Basics Every user of a site is associated with a javax.servlet.http.httpsession object To store and retrieve information about the user Retrieve the current HttpSession object public HttpSession HtttpServletRequest.getSession() Create one if no valid session found 40 Session Attributes To add data to a session object public void HttpSession.setAttribute(String name, Object value) To retrieve an object from a session public Object HttpSession.getAttribute(String name) To get the names of all objects in a session public Enumeration HttpSession.getAttributeNames() To remove an object from a session public void HttpSession.removeAttribute(String name) 41 Session Lifecycle Sessions do not last forever Expire automatically due to inactivity Default 30 min Explicitly invalidated by servlet When session expires (or is invalidated) The HttpSession object and its data values are removed 42 7
HttpSession Lifecycle Methods boolean isnew() Returns true if the client does not yet know about the session or if the client chooses not to join the session void invalidate() Invalidates this session then unbinds any objects bound to it long getcreationtime() Returns the time when this session was created, measured in milliseconds since midnight Jan 1, 1970 GMT long getlastaccessedtime() Returns the last time the client sent a request associated with this session, and marked by the time the container received the request Setting Session Timeout Setting default session timeout Deploy descriptor, web.xml Applies to all sessions created in the given Web application <session-config> <session-timeout> 30 <!--minutes--> </session-timeout> </session-config> Configured individually public void HttpSession.setMaxInactiveInterval(int secs) public int HttpSession.getMaxInactiveInterval() Terminating a session session.invalidate() Deletes session related attributes from server Removes cookie from client 43 44 JSP (Java Server Pages) Servlets disadvantage A little Java in a whole lot of HTML Java Server Pages Embed Java servlet code in HTML pages Deployed in textual form (as opposed to byte code) Translated into a servlet on the fly Server automatically creates, compiles, loads, and runs a special servlet for the page Behind the Scene 45 46 Simple JSP Example JSP Lifecycle <html> <head> <title>jsp Example</title> </head> <body> <h1>jsp Example</h1> <hr> <% out.println("hello " + request.getparameter("name")); %> <p> <%= "Hello again " + request.getparameter("name") + "!"%> </body> </html> 47 48 8
ASP (Active Server Pages) Microsoft-specific technology Similar to JSP Use VisualBasic instead of Java Can access a vast variety of COM and DCOM objects 49 9