11th Chapter Web11-cookie&session

Source: Internet
Author: User

Today's mission
? Displays the last access time of the user
? Login system to display product browsing history
? Buy items Add items to your shopping cart
? Verifying the verification code of the system login
Teaching navigation
Teaching objectives
Understand the simple use of JSPs
Mastering the use of cookies
Mastering the use of the session
Teaching methods
Case-driven approach
1.1 Previous lesson Content review:

  • Set the status code via response: setStatus (int status);
  • The response header is set through response: SetHeader (string name,string value), Setintheader (string name,int value), Setdateheader (string name, Long date);
  • Set the response body via response: Getoutputstream (), getwriter ();
  • Other APIs for response:
    • Sendredirect (String path);
  • Response output Chinese garbled problem:
    • Byte stream output Chinese:
      • Sets the character set encoding for the browser. Response.setheader ("Content-type", "text/html;charset=utf-8");
      • Sets the character set encoding of the byte array for the output content. "". GetBytes ("UTF-8");
        • Character Stream output Chinese:
      • Sets the browser character set encoding. Response.setheader ("Content-type", "text/html;charset=utf-8");
      • Sets the encoding of the response buffer. Response.setcharacterencoding ("UTF-8");
  • Response completed the file download function:
  • Use request to obtain information about the client. Getremoteaddr (), GetMethod (), Getrequesturi (), Getrequesturl ()
  • Get Request Parameters: GetParameter (), Getparametervalues (), Getparametermap ()
  • Access data as a domain object: setAttribute (), getattribute (), RemoveAttribute ();
  • Processing of the Chinese characters of receiving parameters:
    • Get:new String ("". GetBytes ("Iso-8859-1"), "UTF-8")
    • POST:request.setCharacterEncoding ("UTF-8");
  • When was the request created and destroyed?
    • Create: Sends a request from the client to the server. Then the server creates a requester object.
    • Destroy: After the server responds to this request, the server destroys the requests object.
    • Scope of action: one request.
  • Forwarding and redirection differences?
    • Forwarding is a response that requests one time, redirects two requests and two responses.
    • The forwarding Address bar does not change, and redirects change.
    • The forwarded path does not require an engineering name, and redirects require an engineering name.
    • Forwarding can be directed to any website only within the site.
      1.2 Case one: Record the user's last login access time. 1.2.1 Requirements:
      After the user login is completed, you are the X-bit user, and your last access time is: Yyyy-mm-dd.
  • If you visit for the first time, only show that you are the X-user.
  • If it is not the first visit, it shows that you are the X-bit user, and your last access time is: Yyyy-mm-dd.
    1.2.2 Analysis: Technical Analysis:
    "Session Technology"
    ? What is a session: The user opens a browser access page, accesses many pages of the site, and the process of closing the browser when the access is completed is called a session.
    ? Common Session Technologies:
  • Cookie: Saves the data to the client browser.
  • Session: Save the data to the server side.
    ? Why use session technology?
  • Private data, shopping information data is stored in session technology.
    See Tuyi and Figure II
    ? Using session technology:
    "Use of Cookie Technology"
    ? To save data to a browser:
    HttpServletResponse has a method:
  • void Addcookie (cookie cookie);
    ? Get the cookie that the browser brought over:
    HttpServletRequest has a method:
  • Cookie[] GetCookies ();
    ? Create a Cookie object:
  • Cookie (String name,string value);
    "A simple overview of JSP"
    ? What is Jsp:java Server Pages (Java server-side page). JSP = Java code + HTML elements + JSP built-in things
    ? Why the Sun Company launched JSP Dynamic Web Development technology:
  • The servlet technology launched by Sun has been developed for dynamic web development. It is found that the servlet itself has no way to compete with asp,php technology. You want to export the form in a Dynamic Web page. Get PrintWriter out in a servlet Response.getwriter ();
  • Out.println ("<form action=" method= ">");
  • Out.println ("</form>");
  • Sun also launched a dynamic Web development technology is the JSP.
    ? The execution process of the JSP:
  • The JSP is translated into a servlet and compiled into a class for execution.
    ? Embedded Java code for JSP: the scripting element of a JSP
  • <%! %>: Translated into a member part of a class. Define variables, define methods, define classes. The servlet is thread insecure and as few as possible define member properties in the Class!!
  • <%%>: The content inside the service method that is translated into a class. Define variables, define classes, and write code blocks directly.
  • <%=%>: Translated into the service method within the Out.print (); Step Analysis:
    "Step One": Prepare the case for landing.
    "Step Two": In the servlet of the statisticians. Determine if this is the first time you have visited.
    Step three: Depending on whether the information is displayed for the first time, save the current time to the cookie.
    1.2.3 Code Implementation
public class Countservlet extends HttpServlet {private static final long serialversionuid = 1l;protected void Doget (httpse Rvletrequest request, HttpServletResponse response) throws Servletexception, IOException {response.setcontenttype (" Text/html;charset=utf-8 "), Integer count = (integer) this.getservletcontext (). getattribute (" Count ");//RESPONSE.GETW Riter (). println ("

1.2.4 Summary: Common APIs for cookies:
? Common APIs for cookies:

    • GetName ();
    • GetValue ();
    • SetDomain (String domain); --Set a valid domain name for the cookie. Www.baidu.com music.baidu.com
    • SetPath (String path); --Set a valid path for the cookie.
    • Setmaxage (int maxAge); --Set the effective time of the cookie.
      ? The classification of cookies is related to:
    • Session-Level cookies: The default cookie. Closing the browser cookie will destroy it.
    • Persistent-level cookies: You can set the effective time of the cookie. Then close the browser cookie will also exist. Manually destroy persistent cookies. Setmaxage (0)---premise is that valid paths must be consistent.
      1.3 Case TWO: Record the user's product browsing history: 1.3.1 Requirements:
      On the shopping site to browse the information of the goods, merchants in order to retain users, remember some of the previously browsed items.

      1.3.2 Analysis: Technical Analysis: Step Analysis:
      "Step One": Displays the Product List page when the login is complete.
      Step Two: Do some preparatory work for the Product List page.
      "Step three": Click on an item to pass the item ID to a servlet.
      "Step Four": In the servlet: Judging whether it is the first time to browse the product
      "Step Five": If this is the first time: Store the product's ID in a cookie.
      "Step Six": if it is not the first time: Determine whether the product has been browsed.
      "Step Seven": If the browser is over. Delete the previous element and add the element to the front.
      "Step Eight": If you have not browsed the product. Determine the maximum length, no more than the limit, directly add to the front, if you have exceeded the limit, delete the last one, insert it to the front.
      1.3.3 Code implementation:
public class Productservlet extends HttpServlet {private static final long serialversionuid = 1l;protected void Doget (Http ServletRequest request, HttpServletResponse response) throws Servletexception, IOException {/** * * receive Product ID. * Receive from Client All cookies. * * Find the cookie of the specified name from the array of cookies. * * To determine whether it is the first time to browse the product: * * First time to browse the product * * directly to the product's ID into a cookie. * * Write cookies back to the browser. * * Not the first time to view the item 1-2 * * Determine if the current item is already in the browsing history. * * already exists: 2-1 removes the current element and adds the current element to the beginning. * * Not in the browsing record: * * Determine if the maximum length has been exceeded: if more than 2-1-3: Delete the last one adds the current element to the front. * * Not over: Add the element directly to the top position. * * Convert the value of the ID into a cookie and write back to the browser. *///receive id:string id = request.getparameter ("id");//obtain information about all cookies: cookie[] cookies = request.getcookies ();//Determine whether this is the first time: Cookie cookie = Cookieutils.findcookie (Cookies, "history"), if (cookie = = null) {//First view product cookie c = new Cookie ("History", I d); C.setpath ("/day11"); C.setmaxage (60*60*24*7); Response.addcookie (c);} else{//is not the first time to browse//determine if the selected item is already in the browsing record 2-1string value = COOKie.getvalue (); string[] ids = Value.split ("-");//Change the array to a collection:linkedlist<string> list = new Linkedlist<string> (Arrays.aslist ( IDS), if (List.contains (ID)) {/////List.remove (ID);//1-2-3list.addfirst (ID);} else{//has not browsed the product. if (List.size () >=3) {//More than 3 list.removelast (); List.addfirst (ID);} else{//not to 3. List.addfirst (ID);}} Remove the elements from the list, use the-link to save to a cookie, and write back to the browser. StringBuffer sb = new StringBuffer (); for (String s:list) {sb.append (s). Append ("-");} String svalue = sb.tostring (). substring (0,sb.length ()-1); System.out.println (svalue);//deposit into Cookie a cookie c = new Cookie ("History", svalue); C.setpath ("/day11"); C.setmaxage (60* 60*24*7); Response.addcookie (c);} Request.getrequestdispatcher ("/demo2/product_info.htm"). Forward (request, response);} protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { Doget (request, Response);}}

1.3.4 Summary: clear Browsing History:

删除持久性的Cookie:public class ClearServlet extends HttpServlet {private static final long serialVersionUID = 1L;protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Cookie cookie = new Cookie("history",null);cookie.setPath("/day11");cookie.setMaxAge(0);response.addCookie(cookie);response.sendRedirect("/day11/demo2/product_list.jsp");}/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubdoGet(request, response);}}

1.4 Case Three: Add items to your shopping cart: 1.4.1 Requirements:
To view an item's details, add it to your cart. You need to add items to your shopping cart.

1.4.2 Analysis: Technical Analysis:
"Overview of the session"
The cookie itself is limited in size and number. There is no limit to the session. The data of the cookie is saved on the client, and the session data is saved on the server side.
? Session execution Principle: cookie-based.
? Use session:

    • gets session:
      • request.getsession (); Step Analysis:
        Step One: Click Add to Cart submit to servlet
        "Step Two": Store the items in the servlet in the session.
        "Step three": You can create a map collection to save the shopping information map key can be the name of the commodity, map value is the number.
        Step Four: Display the data in the map on the shopping cart page.
        1.4.3 Code implementation:
public class Cartservlet extends HttpServlet {private static final long serialversionuid = 1l;protected void Doget (Httpser Vletrequest request, HttpServletResponse response) throws Servletexception, IOException {//Receive Product Name: String name = new Strin G (Request.getparameter ("name"). GetBytes ("Iso-8859-1"), "UTF-8");//Create a Map collection for saving shopping information .map<string,integer> The key of the map is the name of the commodity value is the number of purchases. map<string,integer> map = (map<string, integer>) request.getsession (). getattribute ("cart"); if (map = = NULL {map = new linkedhashmap<string,integer> ();} Determine if the item has already been bought in the cart. if (map.containskey (name)) {//Map already has this item://* If the item already exists in the cart: Get the number of the item in the map +1. Stored back into the map collection. Integer count = map.get (name); Count++;map.put (name, count);} There is no such product in else{//map./* If the cart does not change the item: Add the item to the map collection in number 1.map.put (name, 1);} * Save the Map collection to the session. Request.getsession (). SetAttribute ("cart", map); Response.setcontenttype ("text/html;charset= UTF-8 "); Response.getwriter (). println (" 

1.4.4 Summary: session is a domain object:
When will the session be created and destroyed? Scope of action:

    • Create: The server side first calls GetSession () to create the session.
    • Destruction: Three cases of destruction session:
      • 1.session expired. The default expiration time is 30 minutes.
      • 2. Disable the server gracefully. If the session is closed properly, serialize to the hard disk.
      • 3. Manually call Session.invalidate ();
    • Scope of Action: multiple requests. (one session)
      1.5 Case FOUR: The verification of one-time validation code 1.5.1 requirements:
      In the login page, you need a verification code.

      1.5.2 Analysis: Technical Analysis:
      Use the session to save the production verification code. Step Analysis:
      "Step One": Generate a verification code that will generate a random 4 letters or numbers of verification code to the session.
      "Step Two": Enter the verification code value in the page, click Submit.
      Step three: Obtain a verification code from the form in the servlet to obtain a verification code from the session.
      Step four: Match the two verification code values.
      "Step Five": Empty the verification code saved in session.
      1.5.3 Code implementation:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// 校验验证码程序:String code1 = request.getParameter("code");String code2 = (String) request.getSession().getAttribute("code");request.getSession().removeAttribute("code");if(!code1.equalsIgnoreCase(code2)){request.setAttribute("msg", "验证码输入错误!");request.getRequestDispatcher("/demo2/login.jsp").forward(request, response);return ;}   ...}

1.5.4 Summary: use JS control picture switch:

<script type="text/javascript">        function changeImg(){        document.getElementById("img1").src="/day11/CheckImgServlet?time="+new Date().getTime();        }</script>

11th Chapter Web11-cookie&session

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.