410 likes | 589 Views
COMPS311F. Li Tak Sing. A web page that counts the number of times that you have visited the page. You can try the page at: http://plbpc001.ouhk.edu.hk/tma/Count You can get the source at: http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/Count.java. Count.
E N D
COMPS311F Li Tak Sing
A web page that counts the number of times that you have visited the page. • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/Count • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/Count.java
Count public class Count extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String count = null; Cookie cookie[] = request.getCookies(); if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("count")) { count = c.getValue(); } } }
Count if (count == null) { out.println("You are new here."); count = "1"; } else { out.println("You have visited this site for " + count + " times."); count = Integer.toString(Integer.parseInt(count) + 1); } response.addCookie(new Cookie("count", count)); } finally { out.close(); } } }
A page that allows that users to select the size of the fonts. • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/FontSize • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/FontSize.java
FontSize public class FontSize extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String size = null; if (request.getParameter("size") != null) { size = request.getParameter("size"); response.addCookie(new Cookie("size", size)); }
FontSize if (size == null) { Cookie cookie[] = request.getCookies(); if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("size")) { size = c.getValue(); } } } } if (size==null) { size="3"; }
FontSize out.println("<font size=" + size + "/>"); out.println("<form>"); out.println("Font size:<select name='size'>"); out.println("<option value='3'>3</option>"); out.println("<option value='4'>4</option>"); out.println("<option value='5'>5</option>"); out.println("</select>"); out.println("<input type='submit' value='submit'/>"); out.println("</form>"); out.println("<p>This text is just used to test the servlet.</p>"); out.println("<p><a href='FontSize'>Click this to reload the page</a></p>"); out.println("</font>"); } finally { out.close(); } } }
Other useful methods of Cookie • public void setDomain(String pattern) • Specifies the domain within which this cookie should be presented. By default, cookies are only returned to the server that sent them. This is the reason why cookie is dangerous. For example, when you visit site A and accept a cookie. Then when you visit site B and sent that cookie to site B. In this way, site B would know that you have visited site A. If that happens to many sites, then site B will now have your profile of internet surfing. • Public String getDomain() • Returns the domain name set for this cookie.
Other useful methods of Cookie • public void setPath(String pattern) • Sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. This method can be used to specify something more general. For example, someCookie.setPath("/") specifies that all pages on the server should receive the cookie. Note that the path specified must include the current directory. • Public String getPath() • Get the path to which this cookie applies.
Other useful methods of Cookie • public void setMaxAge(int expiry) • Sets the maximum age of the cookie in seconds. • A positive value indicates that the cookie will expire after that many seconds have passed. Note that the value is the maximum age when the cookie will expire, not the cookie's current age. • A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted. • If you don't set this, the cookie will last only for the current session (i.e. until the user quits the browser), and will not be stored on disk.publicintgetMaxAge() • Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
A cookie that expires in 10 seconds • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/Expire • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/Expire.java
A cookie that expires in 10 seconds public class Expire extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("create") != null) { Cookie c = new Cookie("expire", "10"); c.setMaxAge(10); response.addCookie(c); } Cookie cookie[] = request.getCookies();
A cookie that expires in 10 seconds intfontsize = 3; if (cookie != null) { for (Cookie c : cookie) { if (c.getName().equals("expire")) { fontsize=10; } } }
A cookie that expires in 10 seconds out.println("<font size='"+fontsize+"'>"); out.println("The font size is "+fontsize+"."); out.println("</font>"); out.println("<form>"); out.println("<input type='submit' name='create' value='create a cookie'/>"); out.println("</form>"); out.println("Click <a href='Expire'>this</a> to revisit this page"); } finally { out.close(); } } }
Attributes of servlets • As a servlet would only be instantiated once in a Web server, all requests to the servlet would use the same copy of the servlet. Therefore, we can define attributes for the servlet if we want them to be shared amoung all users of the servlet.
Differences between attributes of a servlet and cookies • An attribute of a servlet is shared by all users of the servlet. • A cookie is used by only one user. • So if you want to have something to be shared by all users, then use an attribute to store it. • If you only want it to be used by a user, then use a cookie to store it. • When you use an attribute to store a value, make the access to the value thread safe as that value may be accessed by multiple threads at the same time.
An example of a fixed size buffer • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/Buffer • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/Buffer.java
Buffer The code for the buffer: private int data[] = new int[3]; private int no = 0; private synchronized int get() { while (no == 0) { try { wait(); } catch (Exception e) { } } notifyAll(); return data[--no]; }
Buffer private synchronized void put(int num) { while (no == data.length) { try { wait(); } catch (Exception e) { } } data[no++] = num; notifyAll(); }
Buffer protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { if (request.getParameter("get") != null) { inti = this.get(); out.println("The integer got from the buffer:" + i + "<br>"); } else if (request.getParameter("input") != null) { inti = Integer.parseInt(request.getParameter("input").trim()); this.put(i); }
Buffer out.println("Number in the buffer:"); for (inti = 0; i < no; i++) { out.print(data[i] + " "); } out.println(); out.println("<form>"); out.println("put an integer to the buffer:"); out.println("<input type='text' name='input' size='5'>"); out.println("<input type='submit' name='submit' value='put'"); out.println("</form><br>"); out.println("<form>");
Buffer out.println("get an integer from the buffer"); out.println("<input type='submit' name='get' value='get'"); out.println("</form>"); } finally { out.close(); } } }
HttpSection • We have seen how to use cookies to keep session information. • There is another way to handle session information in servlets, which is using HttpSection. • HttpSection is an interface, not a class. Therefore you cannot create an HttpSection directly. • This is created by a method of HttpServletRequest like this:HttpSection sect=req.getSession(true).
getSession() • There are two getSession() method of HttpServletRequest : • HttpSectiongetSession() • This method will always create a session if the request object doesn’t return one. • HttpSectiongetSession(boolean create) • The create parameter specifies whether a session should be created if the request object doesn’t return one. • One import thing: you should get the session object before any response works. Actually, it is better that you get the session at the before of any doGet or doPost methods.
Looking up information associated with a session • HttpSession objects live on the server; they're just automatically associated with the requester by a behind-the-scenes mechanism like cookies or URL-rewriting. • You can use getAttribute("key") to look up a previously stored value.
Some examples of using HttpSession HttpSession session = request.getSession(true);ShoppingCartpreviousItems = (ShoppingCart)session.getAttribute("previousItems");if (previousItems != null) {doSomethingWith(previousItems);} else {previousItems = new ShoppingCart(...);doSomethingElseWith(previousItems);}
Associating Information with a Session • To access a named value, use getAttribute:public object getAttribute(String name) • Returns the object bound with the specified name in this session, or null if no object is bound under the name. • To set a named value, use setAttribute: public void setAttribute(String name, Object value) • Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced. After this method executes, and if the object implements HttpSessionBindingListener, the container calls HttpSessionBindingListener.valueBound.
Comparison of using cookies and HttpSession • When using cookies, we can only deal with Strings. With HttpSession, we can store any types of objects. • Cookies are always stored in client sides and have to be passed over the internet to the server. For HttpSession, the data is stored in the server side and there is no need to go through the unsafe network. • So HttpSession is much better than using cookies.
Redo Count with HttpSession • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/SessionCount • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/SessionCount.java
Redo Count with HttpSession public class SessionCount extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Integer count =(Integer)session.getAttribute("count");
Redo Count with HttpSession if (count == null) { out.println("You are new here."); count = 1; } else { out.println("You have visited this site for " + count + " times."); count++; } session.setAttribute("count", count); } finally { out.close(); } } }
The page that changes font size • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/SessionFontSize • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/SessionFontSize.java
The page that changes font size public class SessionFontSize extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session=request.getSession(); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { Integer size = null; if (request.getParameter("size") != null) { size = Integer.parseInt(request.getParameter("size")); session.setAttribute("size", size); }
The page that changes font size if (size == null) { Cookie cookie[] = request.getCookies(); size=(Integer)session.getAttribute("size"); } if (size==null) { size=3; } out.println("<font size=" + size + "/>"); out.println("<form>"); out.println("Font size:<select name='size'>"); out.println("<option value='3'>3</option>"); out.println("<option value='4'>4</option>"); out.println("<option value='5'>5</option>"); out.println("</select>");
The page that changes font size out.println("<input type='submit' value='submit'/>"); out.println("</form>"); out.println("<p>This text is just used to test the servlet.</p>"); out.println("<p><a href='FontSize'>Click this to reload the page</a></p>"); out.println("</font>"); } finally { out.close(); } } }
Other useful methods of HttpSession • public void setMaxInactiveInterval(int interval) • Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. A negative time indicates the session should never timeout. • publitintgetMaxInactiveInterval() • Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses. After this interval, the servlet container will invalidate the session. The maximum time interval can be set with the setMaxInactiveInterval method. A negative time indicates the session should never timeout.
A session that expires after 10 seconds of being inactive • You can try the page at: • http://plbpc001.ouhk.edu.hk/tma/SessionExpire • You can get the source at: • http://plbpc001.ouhk.edu.hk/~mt311f/2010-oct/SessionExpire.java
ExpireSession public class SessionExpire extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { HttpSession session; if (request.getParameter("create")!=null) { session=request.getSession(); session.setMaxInactiveInterval(10); } else { session=request.getSession(false); }
ExpireSession response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { intfontsize = 3; if (session!=null) { fontsize=10; }
ExpireSession out.println("<font size='"+fontsize+"'>"); out.println("The font size is "+fontsize+"."); out.println("</font>"); out.println("<form>"); out.println("<input type='submit' name='create' value='create a session'/>"); out.println("</form>"); out.println("Click <a href='Expire'>this</a> to revisit this page"); } finally { out.close(); } } }