[Web programming] Experiment: application of conversational technology

1. Purpose of the experiment

(1) Master the two session tracking technologies of Cookie and session and their application and difference.

(2) Master the application and difference between Cookie and session.

2. Experimental content

(1) Please design a class that uses Cookie technology to realize the function of displaying the user's last visit time.

Requirements are as follows:

Create a LastAccessServlet class, make it inherit the HttpServlet class and rewrite the doGet() method of this class.

In the doGet() method, use request.getCookies() to get the cookie array formed by all cookies and traverse it. If the lastAccess attribute is found in the cookie information during the traversal process, it will be output, otherwise create a cookie object and set the value to the current time and send it to the client. The survival time of the cookie is 1 hour, and all resource clients accessing the current application will return the cookie information.

(2) Please design a program that uses Session technology to realize the shopping cart function.

3. Experimental requirements

(1) Cookie object, master the use of Cookie object

(2) Understand what is a Session object and master the use of the Session object

(3) Learn to use the Session object to implement the shopping cart and user login functions

(4) Carefully record the test process and analyze the cause of the error

(5) Summarize the operation steps

4. Experimental steps and results (including program code and running screenshots)

(1) Please design a class that uses Cookie technology to realize the function of displaying the user's last visit time.

Requirements are as follows:

· Create a LastAccessServlet class, make it inherit the HttpServlet class and rewrite the doGet() method of this class.

 · In the doGet() method, use request.getCookies() to get the cookie array formed by all cookies, and traverse it.

Method and code screenshot:

package com.servlert;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LastAccessServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //编码
        req.setCharacterEncoding("UTF-8");
        resp.setCharacterEncoding("UTF-8");

        Cookie[] cookies=req.getCookies();
        for(int i=0;i<cookies.length;i++){
            System.out.println("Cookie"+cookies[i]);
        }
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Screenshots of code and console output:

 · If the lastAccess attribute is found in the cookie information during the traversal process, it will be output, otherwise create a cookie object and set the value to the current time and send it to the client. The survival time of the cookie is 1 hour, and all resource clients accessing the current application will return the cookie information.

Class implementation code:

package com.servlert;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

public class LastAccessServlet extends HttpServlet {

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         // Encoding req.setCharacterEncoding( "UTF-8" ); // Set the encoding format of the server output content to UTF-8 to prevent garbled characters resp.setContentType( "text/html;charset=utf-8" ) ;        String lastAccessTime = null ; // Get all Cookie information, loop through Cookie[] cookies=req.getCookies(); for ( int i=0;i<cookies.length ; i++){ if ( "lastAccess" .equals (cookies[i].getName())) { // If the cookie name is
        
        
        

        
        
        
            
                lastAccess, then get the value of the cookie lastAccessTime = cookies[i].getValue(); System.out                 .println ( " lastAccess attribute: " +lastAccessTime); break ;            }        } // Calculate whether there is a cookie named lastAccess if ( lastAccessTime == null ) {             resp.getWriter().print( " Your first visit to this website! " );        } else {             resp.getWriter().print( " The last time you visited this website is:  " + URLDecoder.
                

                


        
        



                    decode (lastAccessTime, "UTF-8" ));
        }
         // Create a cookie and send the current time as the cookie value to the client String currentTime = new SimpleDateFormat( "yyyy-MM-dd hh:mm:ss" )                .format ( new Date());        Cookie cookie = new Cookie( "lastAccess" ,                URLEncoder.encode(currentTime, "UTF-8" ));        cookie.setMaxAge(60*60); // Set the maximum lifetime of the cookie // Send
        





        cookie
        resp.addCookie(cookie);
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

Code screenshot:

 Run the screenshot:

 

 

(2) Please design a program that uses Session technology to realize the shopping cart function.

Design ideas and steps:

1. When you click to add to the shopping cart, submit it to a servlet . add2CartServlet
        needs to carry the name of the product in the past. 2. The operation in add2CartServlet         gets the name of the product         and adds the product to the shopping cart. The structure of the shopping cart Map<String name, Integer purchase quantity >             Put the shopping cart into the session and         add the product to the shopping cart Analysis:             Get the shopping cart             to judge whether the shopping cart is empty                 If it is empty:                     Add for the first time                     Create a shopping cart                     and put the current product into it. Quantity: 1                     will Put the shopping cart into the session                 if it is not empty: continue to judge whether there is the product in the shopping cart                     If yes:                         take out the count and add the quantity + 1                         Put the product into the shopping cart again                     If not:                         put the current product in Quantity: 1
     



        














                    
        Prompt information: your xx has been added to the shopping cart
    3. When you click on the shopping cart connection, cart.jsp
        obtains the shopping cart from the session
            to determine whether the shopping cart is empty
                If it is empty: prompt information

                If it is not empty: just traverse the shopping cart

Servlet implementation class code and code screenshot:

package com.servlert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 添加到购物车
 */
public class Add2CartServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // Set encoding response.setContentType( "text/html; charset=utf-8" );         PrintWriter w =response.getWriter(); // Get the name of the product String name=request.getParameter( "name" );         name = new String(name.getBytes( "iso8859-1" ), "utf-8" ); // Add the product to the shopping cart // Get the shopping cart from the session Map<String,Integer> map=(Map<String, Integer>) request.getSession().getAttribute( "cart" );
        


        
        



        

        
        

        Integer count= null ;

        // Judge whether the shopping cart is empty if (map== null ) { // The first login creates a shopping cart map= new HashMap<>(); // Put the shopping cart into the session request.getSession ().setAttribute( "cart" , map);             count= 1 ;         } else { // The shopping cart is not empty Continue to judge whether the shopping cart has the product count=map.get(name); if (count== null ) { // There is no such item in the shopping cart count= 1 ;             } else { //
        
            
            

            
            


            
            

            
                
                

                There is this product count++ in the shopping cart ;             }        } // Put the product into the shopping cart map.put(name, count); // Prompt information w.print( " <b>" +name+ " has been added to the shopping cart <hr>" );        w.println( " <a href='" +request.getContextPath()+ "/product_list.jsp'> Continue Shopping </a> " );        w.println( "<a href=' " +request.getContextPath()+ "/cart.jsp'>View shopping cart </a> " );    } protected void doPost(HttpServletRequest request,HttpServletResponse response) throws
                



        
        

        
        





    ServletException, IOException {

        doGet(request, response);
    }

}

 jsp page code and code screenshot:

product_list.jsp page code and screenshot:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>index页面</title>
  </head>
  <body>
  <div style="margin:20px 0 10px 0;;text-align: center;">
    <a href="Add2CartServlet?name= clothes " >
      < input style =" background : url ( '/1669465431435.webp' ) no-repeat scroll 0-600 px rgba (0,0,0,0); height :36 px ; width :127 px ; " value = " add to shopping cart " type = "button" >
    </ a >Favorite product</div>

  </div>
  </body>
</html>

 Cart.jsp page code and screenshot:

<%@ page import="java.util.Map" %><%--
  Created by IntelliJ IDEA.
  User: 86184
  Date: 2022/11/26
  Time: 20:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<table  border="1" align="center" width="20%">
    <tr>
        <td>商品名称</td>
        <td>商品数量</td>
    </tr>
    <%get shopping cart
        
        Map<String,Integer> map =(Map <String,Integer>)session.getAttribute( "cart" );
        // Judge whether the shopping cart is empty if (map== null ){ // If it is empty, dear, shopping The cart is empty, go shopping first ~~~ out.print( "<tr><td colspan='2'> dear, the shopping cart is empty, go shopping first ~~~</td></tr>" );         } else { // If it is not empty , traverse the shopping cart for (String name :map.keySet()){                 out.print( "<tr>" );                 out.print( "<td>" );                 out.print(name);                out.print("</td>");
        
            
            

            
            





                out.print("<td>");
                out.print(map.get(name));
                out.print("</td>");
                out.print("</tr>");

            }
        }

    %>
</table>

<hr>
<center>
    <a href="product_list.jsp" >继续购物</a>

</center>

 Running effect diagram:

Screenshot of the list page:

 After clicking the shopping cart:

 After clicking to continue shopping:

 After clicking to view cart:

 5. Experimental reflection

(1) Click "Add to Shopping Cart" to enter the successfully added page, a null pointer exception occurs, no product information is obtained, request.getParameter( "name" ) is empty, and finally it is found that the name on the page is inconsistent with the name in getParameter .

(2) There is no information when the shopping cart list is displayed, and it is found that the product information has not been put into the Map.

(3) When accessing all the resources in the current application, the client sends back cookie information, and the output time and other information are not seen on the page. After investigation, it is found that there is a problem with the package imported by out, and there is also a problem with the returned location.

(4) When comparing whether there is a lastAccess attribute in the cookie, during the comparison process, I found that the value I obtained was a null value. I checked the break point line by line, and found that there was a problem with the position of the value definition, and it was defined as a local variable. placed in the loop method.

Guess you like

Origin blog.csdn.net/lf21qp/article/details/131370728