COMP9321 Web Applications Engineering: Java s Service Oriented Computing Group, CSE, UNSW Week 2 H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 1 / 1
Different Layers in an Application Different solutions for each layer Presentation Layer JSP, XSLT, CSS, HTML Business logic Java classes Data Access Layer Data Access Objects Data Store RDBMS, OODBMS, XML Database H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 2 / 1
MVC pattern Browser response request Container 1 (Controller) 4 2 JSP (View) 3 JavaBean (Model) 5 Data request Server H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 3 / 1
Java s A Java technology for generating dynamic content. Used to process HTTP request and generate HTTP response. s are executed by a servlet container containers are web server extensions (eg., Apache Tomcat) that provide servlet functionality. http://java.sun.com/products/servlet/index.jsp Web Server Web Browser HTTP Request (URL + data) request Container classes <FORM> <INPUT> parameters... </INPUT> </FORM> HTTP Response: HTML (+javascript) response (content produced from servlet) DB H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 4 / 1
Java s A Java technology for generating dynamic content. Used to process HTTP request and generate HTTP response. s are executed by a servlet container containers are web server extensions (eg., Apache Tomcat) that provide servlet functionality. http://java.sun.com/products/servlet/index.jsp Web Server Web Browser HTTP Request (URL + data) request Container classes <FORM> <INPUT> parameters... </INPUT> </FORM> HTTP Response: HTML (+javascript) response (content produced from servlet) DB H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 4 / 1
Java s A Java technology for generating dynamic content. Used to process HTTP request and generate HTTP response. s are executed by a servlet container containers are web server extensions (eg., Apache Tomcat) that provide servlet functionality. http://java.sun.com/products/servlet/index.jsp Web Server Web Browser HTTP Request (URL + data) request Container classes <FORM> <INPUT> parameters... </INPUT> </FORM> HTTP Response: HTML (+javascript) response (content produced from servlet) DB H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 4 / 1
Java s A Java technology for generating dynamic content. Used to process HTTP request and generate HTTP response. s are executed by a servlet container containers are web server extensions (eg., Apache Tomcat) that provide servlet functionality. http://java.sun.com/products/servlet/index.jsp Web Server Web Browser HTTP Request (URL + data) request Container classes <FORM> <INPUT> parameters... </INPUT> </FORM> HTTP Response: HTML (+javascript) response (content produced from servlet) DB H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 4 / 1
Java s A Java technology for generating dynamic content. Used to process HTTP request and generate HTTP response. s are executed by a servlet container containers are web server extensions (eg., Apache Tomcat) that provide servlet functionality. http://java.sun.com/products/servlet/index.jsp Web Server Web Browser HTTP Request (URL + data) request Container classes <FORM> <INPUT> parameters... </INPUT> </FORM> HTTP Response: HTML (+javascript) response (content produced from servlet) DB H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 4 / 1
Tomcat Web container structure bin (star/stop the server), common/lib (shared libraries, Tomcat-wide) conf (server configuration files) webapps (Web application base directory) The structure of a Web Application Archive (.war): simple.war\ index.html WEB-INF\ lib classes\myfirst.class web.xml To access the Web app: http://localhost:8080/simple/index.html H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 5 / 1
Making servlets available in the Web container 1 Create the standard Web application directory structure 2 Write a servlet 3 Compile 4 Write a deployment descriptor (web.xml) 5 Package all up into an archive file and name it appname.war 6 Copy the war file into $CATALINA HOME/webapps 7 The server detects the application and makes it available to the users: http://localhost:8080/appname/ There are tools developed designed to assist the programmers with the series of tasks involved in writing Web applications. e.g., Ant tasks for Tomcat, Eclipse Web Tools Platform (WTP) H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 6 / 1
How the Container handles a request ((HeadFirst) p.42) HTTP Request Container Client Web Server Machine Container HttpResponse Client HttpRequest Client Container request response thread H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 7 / 1
How the Container handles a request ((HeadFirst) p.42) Container request thread response service() Container response Generated Content thread service() doget() HTTP Response Generated Content Container request thread Client response H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 8 / 1
Your inherits lifecycle methods <<interface>> service(request, Response) init(config) destroy() getconfig() getinfo() javax.servlet.* javax.servlet.http.* Generic service(request, Response) init(config) destroy() getconfig() getinfo() getinitparameter(string) getinitparameternames() getcontext() log(string) Http service(request, Response) service(httprequest, HttpResponse) doget(httprequest, HttpResponse) dopost(httprequest, HttpResponse) dohead(httprequest, HttpResponse) doput(httprequest, HttpResponse) dooptions(httprequest, HttpResponse) My doget(httprequest,httpresponse) mybusinessmethod() H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 9 / 1
A typical looks like this package com.comp9321; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class One extends Http { public void doget (HttpRequest req, HttpResponse res) throws Exception, IOException { } } res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); java.util.date today = new java.util.date(); out.println("<html><body><h1>one says it is now: "); out.println(today + "</H1></BODY></HTML>"); out.close(); Note: No main() - the container calls the servlet methods like doget() through service()... How does the container know which servlet to call? H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 10 / 1
Names A servlet may have three names Name that the client uses Name that used at deployment time Actual class name (i.e., One.class) All these names are declared and mapped in the deployment descriptor (web.xml) Mapping servlet names improves your app s flexibility and security in web.xml <web-app xmlns="http://java.sun.com/xml/ns/j2ee"... <servlet> <servlet-name>one</servlet-name> <servlet-class>com.comp9321.one</servlet-class> </servlet> <servlet-mapping> <servlet-name>one</servlet-name> <url-pattern>/oneservlet</url-pattern> </servlet-mapping>... URL to the servlet - http://localhost:8080/myapplication/oneservlet H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 11 / 1
A Lifecycle of a The Web container controls the lifecycle of a servlet class Web Container Class Object Container load class 100101 000001 1010 10 000101 Instantiate servlet init() service() initia lised handle client requests (doxx()) destroy() initia lised H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 12 / 1
s Life ((HeadFirst) p.99) lifecycle calls init() When it s called What it s for Override it? Container calls init() after the Gives you a chance to initialise No* servlet instance is created but your servlet before han- before the serlvet can service dling any requests client s requests service() When the first client request comes in, the container starts a new thread and calls service() method doxx() The service() method invokes appropriate doxx() This one looks at the request and determines the HTTP method and invokes the matching doxx() on the servlet This is where your code begins. This is the method that is responsible for whatever the servlet is supposed to be doing * Maybe... (e.g., getting a database connection), but not always No. Always H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 13 / 1
Why care about this initialisation details? (HeadFirst) p.104 Once the servlet is initialised, the servlet gets access to two important objects: A Config object: One Config object per servlet Use it to pass deploy-time information to the servlet (any info. that you do not want to hard-code into the servlet) Use it to access the Context Parameters are configured in the deployment descriptor A Context One Context per Web application (they should have named it AppContext) Use it to access parameters that are Web application-wide Use it as a kind of application bulletin-board, where you can put up info (called attributes) that other parts of the application can access Use it to get server info, including the name and version of the container, etc. H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 14 / 1
Why care about this initialisation details? (HeadFirst) p.104 does not exist Context App.-Wide params constructor init(config) destroy() JSP A service() (initialised) A B C By the time servlet is running doxx(), it's got a Config Config Config Config -Wide params Config H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 15 / 1
Config: Passing servlet configuration information The Web container can pass some configuration information (eg., initial parameters) for individual servlets... in web.xml: <web-app> <servlet> <servlet-name>demo</servlet-name> <servlet-class>com.comp9321.configdemo</servlet-class> <init-param> <param-name>webmaster</param-name> <param-value>helen Paik</param-value> </init-param> <init-param> <param-name>webmasteremail</param-name> <param-value>hpaik@webmaster.com</param-value> </init-param> </servlet> <servlet> <servlet-name>seconddemo</servlet-name> <servlet-class>com.comp9321.nextdemo</servlet-class> <init-param> <param-name>language</param-name> <param-value>italian</param-value> </init-param> </servlet> </web-app> H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 16 / 1
Who s responsible for what? Container or Creates the request and response objects? Calls the service() method? Adds HTML content to the response object? Has a name that matches the <servlet-class> element in the DD? Has a reference to the response objects? Finds the URLs in the DD? Starts a new thread to handle requests? Setting the content type of the response? H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 22 / 1
The difference between GET and POST GET /myapp/selectbeertaste.do?colour=dark&taste=malty HTTP/1.1 HOST:www.cse.unsw.edu.au User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-us Accept: text/xml, application/xml, application/xhtml+xml, text/html, video/x-mng, image/png Accept-Language: en-us Connection: Keep-alive POST /myapp/selectbeertaste.do HTTP/1.1 HOST:www.cse.unsw.edu.au User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-us Accept: text/xml, application/xml, application/xhtml+xml, text/html, video/x-mng, image/png Accept-Language: en-us Connection: Keep-alive colour=dark&taste=malty BODY (payload) New Empty Line H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 23 / 1
The difference between GET and POST Sensitive data should NOT be used with GET GET s parameter data shows up in the browser s input bar POST cannot be bookmarked If you want to let users specify search parameters and save it for later, cannot use POST GET is supposed to be used for getting things - information retrieval POST is supposed to be used for sending data to be processed - update or change something on the server GET Sends back a response with a generated HTML page POST uses the POST data to update the database Sends back a response with a generated HTML page DB H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 24 / 1
What determines whether the browser sends GET/POST GET (HeadFirst) p.117 POST GET <A HREF="http://www.cse.unsw.edu.au/myapp/index.html>click here</a> <form method="post" action="selectbeer.do"> Select Beer<p> <option>light <option>amber <option>dark </select> <center> <input type="submit"> </center> </form> <form action="selectbeer.do"> Select Beer<p> <option>light <option>amber <option>dark </select> <center> <input type="submit"> </center> </form> What if I want to support both GET and POST? public void dopost(...) throws { doget(request, response) } H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 25 / 1
Request & Response Interfaces <<interface>> javax.servlet.request getattribute(string) getcontentlength() getparameternames() getparameter() // Many more methods... <<interface>> Response getbutffersize() setcontenttype() getwriter() // Many more methods... <<interface>> javax.servlet.http.httprequest getcontextpath() getcookies() getheader(string) getquerystring() getsession() //Many more methods <<interface>> javax.servlet.http.httpresponse addcookies() addheader() encoderedirecturl() senderror()... //Many more methods The container implements HttpRequest and HttpRequest All you should care about is when servlet is called the service() passes two objects that implements the two to your servlet H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 26 / 1
HttpRequest, HttpResponse The service() method invokes appropriate doxxx() method when the servlet receives an HTTP request. Typically, your (http) servlet code would have the following structure: import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class My extends Http { public void doget(httprequest req, HttpResponse res) throws IOException, Exception { // your code to generate response... } public void dopost(httprequest req, HttpResponse res) throws IOException, Exception { // your code to generate response... } HTTP request method determines whether doget() or dopost() runs. H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 27 / 1
A simple servlet that generates a text message import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Static extends Http { public void doget(httprequest request, HttpResponse response) throws IOException, Exception { response.setcontenttype("text/html"); PrintWriter out = response.getwriter(); out.println("<html>"); out.println("<body>"); out.println("<head>"); out.println("<title>static </TITLE>"); out.println("</head>"); out.println("<body>"); out.println("<center><h1>hello folks!</h1></center>"); out.println("</body>"); out.println("</html>"); } } H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 28 / 1
When you do not want to process the response yourself if (worksforme) { // handle the request } else { response.sendredirect("http://www.cse.unsw.edu.au/myapp/new"); } Redirection (sendredirect()) Type in a URL (HeadFirst) p.134-136 new URL (status code 301 and location) The servlet decides that the request should go to a different URL Redirect The servlet calls sendredirect(astring) on the response Sends request for the new URL final response Another H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 35 / 1
Request Dispatching You may want to: include the output from another servlet delegate (forward) the request processing to another servlet include a static HTML content You can use methods in the RequestDispatcher interface: include: to include content from another resource public void include(httprequest req, HttpResponse res) forward: forward a request to another servlet public void forward(httprequest req, HttpResponse res) H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 36 / 1
Request Dispatching You may want to: include the output from another servlet delegate (forward) the request processing to another servlet include a static HTML content You can use methods in the RequestDispatcher interface: include: to include content from another resource public void include(httprequest req, HttpResponse res) forward: forward a request to another servlet public void forward(httprequest req, HttpResponse res) H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 36 / 1
Forwarding a request to another servlet Using include(): The called servlet can only alter the body of the response, and not the headers. The path information of the request also continues to reflect the original request location. Using forward(): no content may have been committed to the client (eg., flushbuffer()) the called servlet can adjust the headers as well as the body of the response (content produced up to the forward call is cleared from the buffer). The path information of the request is altered to reflect the location of the called servlet, and no further output can occur after returning from a forward call (the output is committed upon returning from the call). H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 41 / 1
Forwarding a request to another servlet Using include(): The called servlet can only alter the body of the response, and not the headers. The path information of the request also continues to reflect the original request location. Using forward(): no content may have been committed to the client (eg., flushbuffer()) the called servlet can adjust the headers as well as the body of the response (content produced up to the forward call is cleared from the buffer). The path information of the request is altered to reflect the location of the called servlet, and no further output can occur after returning from a forward call (the output is committed upon returning from the call). H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 41 / 1
Attributes and Sharing Attributes An attribute is an object bound to one of the following objects: Context (web-app wide object!) HttpRequest HttpSession an attribute is simply a name/value pair - name is a String and attribute is an Object. Think of it an object pinned onto a board. Somebody sticks it on the board so that others can get it... A Bulletin Board Attributes C B Customer Helen Course COMP9321 Choice DarkColour D H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 44 / 1
Who has access to the board and how long does it live? read read write Context Attributes DB Connection ConcurrentUsers 42 AdminEmail xx@xxxx read read (HeadFirst, p.187) JSP Everyone in the application has access Session Attributes read write Shopping Cart A UserName Helen read JSP Accessible to only those with access to a specific HttpSession write Request Attributes OptionChoice Dark Beer read JSP Accessible to only those with access to a specific (Http)Request H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 45 / 1
Attributes API (HeadFirst, p. 189) Context <<interface>> Context getinitparameters(string) getinitparameternames() getattribute(string) setattribute(string, Object) removeattribute(string) getattributenames() getmajorversion() getinfo() // Many more methods... Request <<interface>> Request getcontexttype() getparameter() getattribute(string) setattribute(string, Object) removeattribute(string) getattributenames() // Many more methods... Session <<interface>> HttpSession setmaxinactiveinterval() getlastaccessedtime() getattribute(string) setattribute(string, Object) removeattribute(string) getattributenames() // Many more methods... <<interface>> HttpRequest //Nothing related to attributes here... H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 46 / 1
Attributes are not parameters (HeadFirst, p. 186) Types Attributes Context (Web App.) Request, Session Parameters context init params request params, servlet init params Method to set setattribute(string name, In DD and via client input Object value)... Return type Object String Method to get getattribute(string name) getinitparameters(string name) no such thing as Session parameters Object returned from getattribute() has to be casted. H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 47 / 1
Request attributes and Request dispatching We use request attributes when you want some other component of the application take over all or part of your request. // code in doget() String postcode = getpostcode(request.parameter("suburb"); request.setattribute("pc", postcode); RequestDispatcher view = request.getrequestdispatcher("displaypostcode.jsp"); view.forward(request, response); // the JSP will use the attribute pc to access the postcode. There is no reason to use context or session attributes, since it only applies to this request (so request scope is enough). H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 48 / 1
Managing the user state In most web applications: The user needs to have continuous one-on-one interactions with the application. The user builds up data which may have to be shared across multiple pages in the application. eg., Think of a shopping cart or a flight booking... H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 49 / 1
Managing the user state A problem in HTTP request/response: Web applications need to maintain a user + his/her data. HTTP is a stateless protocol. A single request/response Nothing is remembered between requests from the same user It is a programmer s responsibility: The term session is used to represent the data associated with one user while s/he navigates around a Web applicaiton. A web application may concurrently host several sessions (i.e., multiple users). H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 50 / 1
Session Management request 1. Diane (HeadFirst) p.226 Request to recommend a Dark Beer response: What price range? Web container Beer Thread a response: What price range? Data for setattribute(): Diane Stores "Dark Beer" for Diane request 2. Diane request 1. Selects "Expensive" response: Guiness Web container Request to recommend a Wheat Beer Terri response: What price range? response: Guiness Beer Thread b response: What price range? Thread c Data for Diane Data for Terri H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 51 / 1
How does the container know who the client is? The client needs a unique Session ID request 1. request, dark new! - generate an ID ID#4123 Session Diane response, ID#4123 Web container setattribute(): Stores "Dark Beer" for Diane request 2. Diane request 1. request, Expensive, ID#4123 response, ID#4123 Terri request, wheat existing ID! request, ID#4123 HttpRequest new! - generate ID Web container response, ID#5555 ID#5555 Session ID#4123 Session setattribute(): Stores "Wheat Beer" for Terri H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 52 / 1
Session Management There are a number of ways to deal with sessions. The basic idea: When a user request comes in, besides sending the response, the container also sends an identifier the identifier is recorded by the server When the container receives a request with the same identifier, it can treat the request as belonging to the same user There are four techniques available: Without the container s help: URL rewriting HTML hidden fields Cookies With the container s help: HTTP Session objects H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 53 / 1
URL Rewriting In this method, you append a token or identifier of the session to the URL of the next servlet (or resource). http://myserver:port/comp9321/nextservlet?userid=22987600 (inside nextservlet) request.getparameter("userid"); You need to consider several things: URL cannot be longer than 2,000 characters Special characters such as &,? or spaces should be encoded The values you pass can be seen in the URL H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 54 / 1
HTML hidden fields A token or identifier is passed as the value for an HTML hidden field in a form. <FORM METHOD=POST ACTION="/nextservletl"> <INPUT TYPE="hidden" NAME="token" VALUE="990088"> <INPUT TYPE="hidden" NAME="allowed" VALUE="true"> <INPUT TYPE="submit" NAME="Continue"> (inside nextservlet) request.getparameter("token"); request.getparameter("allowed"); URL cannot be seen by the user but you still can read them from viewing the HTML source. an HTML form is always required in every page H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 55 / 1
Cookies A cookie is a small data item that was introduced to maintain HTTP state by Netscape around 1994. A cookie is created by the server and sent to a browser inside a header. It is subsequently used by the server The browser does not interpret cookies Cookies are kept in the browser s memory, or can be written to a file for future references Eg., Inside a cookie file Set-Cookie: username="joe"; path="/"; domain="www.comp9321.com"; expires="2003-06-01 00:00:00GMT"; version=0 H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 56 / 1
Cookies In servlet programming, a cookie is represented by the Cookie class in the javax.servlet.http package. Cookie c1 = new Cookie("myCookie", "secret"); You then can add the cookie to the HTTP response using the addcookie method of the HttpResponse interface: response.addcookie(c1); Note that because cookies are carried in the request and response headers, you must not add a cookie after an output has been written to the HttpResponse object. setdomain() getdomain() setmaxage() getmaxage() setpath() getpath() getname() setvalue() H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 57 / 1
HTTP Sessions with JSESSIONID cookie The most convenient way of managing sessions is through the Session object, represented by the javax.servlet.http.httpsession interface For each user, the container creates an HttpSession object to be associated with that user The HttpSession object acts like a Hashtable into which you can store any number of key/object pairs (called HttpSession Attributes) An HttpSession object relies on a cookie or URL rewriting to send a token to the client. The token is usually a unique number called the session identifier (JSESSIONID). This session identifier is used to associate a user with a Session object in the server. H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 60 / 1
HTTP Sessions Interface Request HTTP/1.1 200 OK Set-Cookie: JSESSIONID=0AAB6C8DE415 Content-Type: text/html Content-Lengh: 397 Date: Wed, 19 Nov 2005 03:25:40 GMT Server: Apache 1.1 Connection: close <html>... </html> Set Cookie Web container Next Request POST /select/beerpricerange HTTP/1.1 Host: www.cse.unsw.edu.au User-Agent: Mozilla 5.0 Cookie: JSESSION=0AAB6C8DE415 Accept: next/xml,application/xml,application/xhtml Accept-Language: en-us Web container H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 61 / 1
An example of using HttpSession object: the scenario Issue Welcome Start Session Welcome Create a Journey object for the user Display Choices Menu Add Choice to Journey Show Journey so far Control Close Session Enough H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 62 / 1
The Journey Object In a Journey object, a record of the user s proposed travel destinations is maintained. import java.util.*; import java.io.serializable; public class Journey implements Serializable { private Vector Places; public Journey() { Places = new Vector(); } public Iterator getplaces() { return this.places.iterator(); } public boolean addplace(string place) { return Places.add(place); } } public String tostring() { return "Journey to "; } H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 63 / 1
Using a Journey Object The following segment of code: 1 initialises a new Journey object, 2 adds VIC then NSW then QLD to the journey, 3 then (iii) print out the all the places on the route. Journey jny = new Journey(); jny.addplace("vic"); jny.addplace("nsw"); jny.addplace("qld"); Iterator i = jny.getplaces(); while (i.hasnext()) System.out.println("- "+ i.next()); H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 64 / 1
How session tracking works... User request response Travel-Application Welcome request response (sessid=50) request (sessid=50) response (sessid=50) request (sessid=50) response Menu Control Enough (In the servlet container) SessionTable s25 user1 s29 user2 s36 user3 s50 user4 new entry for the new user SessionData id attribute address s25 s29 s36 s50 "JourneyFlag" "Queue" "Patron" "JourneyFlag" Memory jny2 obj jny obj SA WA H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 69 / 1
When Cookie is disabled by the client... The container uses URL rewriting as a fall back method. public class Menu extends Http { public void dopost (HttpRequest req, HttpResponse res) throws Exception, IOException { res.setcontenttype("text/html"); PrintWriter out = res.getwriter(); HttpSession session = req.getsession(); out.println("<html><body>"); out.println("<a HREF=" + response.encodeurl("/controler") + ">Next Page</A>"); out.println("</body></html>"); encodeurl() adds the extra sessionid info to the given URL (e.g., http://... /Controler;JSESSIONID=AJKN88809) you need to use encodeurl for all URLs. H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 73 / 1
Getting rid of Sessions Three ways a session can die: It times out You can call invalidate() on the session object The application goes down (e.g., crashed or undeployed) Configuring session timeout in DD (in minutes) <web-app...> <servlet>... </servlet> <session-config> <session-timeout>15</session-timeout> </session-config> </web-app> Setting session timeout for a specific session (in seconds) session.setmaxinactiveinterval(20*60); H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 74 / 1
s... Web Server Web Browser HTTP Request (URL + data) request Container classes <FORM> <INPUT> parameters... </INPUT> </FORM> HTTP Response: HTML (+javascript) response (content produced from servlet) DB Is Java-based technology for generating dynamic HTTP content. A servlet lifecycle is managed by Container Follows the request/response paradigm Implements methods (eg., doget()) to process HTTP requests Session tracking using HttpSession objects H. Paik (CSE, UNSW) COMP9321, 13s2 Week 2 75 / 1