1 / 7

CS6320 – Servlet Cookies

CS6320 – Servlet Cookies. L. Grewe. What is a cookie?. Name-value bindings sent by a server to a web browser and then sent back unchanged by the browser each time it accesses that server. e.g. login = grewe (name = value)

sheila
Download Presentation

CS6320 – Servlet Cookies

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS6320 – Servlet Cookies L. Grewe

  2. What is a cookie? • Name-value bindings sent by a server to a web browser and then sent back unchanged by the browser each time it accesses that server. • e.g. login = grewe (name = value) • Used for authenticating, tracking, and maintaining specific information about users, such as site preferences or the contents of their electronic shopping carts.

  3. Servlets and Cookies • Java Servlet API provides comfortable mechanisms to handle cookies • The class javax.servlet.http.Cookierepresents a cookie • Getter methods: • getName(), getValue(), getPath(), getDomain(), getMaxAge(), getSecure()… • Setter methods: • setValue(), setPath(), setDomain(), setMaxAge()…

  4. Servlets and Cookies (cont) • Get the cookies from the service request: Cookie[]HttpServletRequest.getCookies() • Add a cookie to the service response: HttpServletResponse.addCookie(Cookie cookie)

  5. Webpage that triggers Servlet to create a Cookie getname.html <html> <head><title>Insert your Name</title></head> <body><h1>What is your name?</h1> <formaction="welcomeback" method="get"> <p> <inputtype="text" name="username" /> <inputtype="submit" /> </p> </form> </body> </html>

  6. An Example (cont) WelcomeBack.java publicclass WelcomeBack extends HttpServlet { publicvoid doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { String user = req.getParameter("username"); if (user == null) { // Find the "username" cookie Cookie[] cookies = req.getCookies(); for (int i = 0; cookies != null && i < cookies.length; ++i) { if (cookies[i].getName().equals("username")) user = cookies[i].getValue(); } } else res.addCookie(new Cookie("username", user));

  7. An Example (cont) if (user == null) // No parameter and no cookie res.sendRedirect("getname.html"); res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html><body><h1>Welcome Back " + user + "</h1></body></html>"); } } WelcomeBack.java

More Related