Home > Java > javaTutorial > Introduction to graphic code of servlet session in Java

Introduction to graphic code of servlet session in Java

黄舟
Release: 2017-07-27 15:18:37
Original
1343 people have browsed it

This article mainly introduces the introduction of servlet session. The editor thinks it is quite good. Now I will share it with you and give it as a reference. Let's follow the editor and take a look.

Session is a server-side technology. Using this technology, the server can create a exclusive session object for each user's browser during runtime. Note that By default, a browser occupies one session. Since the session is exclusive to the user's browser, when users access the server's web resources, they can store their own data in their own sessions. When the user accesses the server again, When accessing other web resources, other web resources then retrieve data from the user's respective session to serve the user.

The main difference between Session and Cookie:

Cookie technology is a client-side technology, in which the server writes the user's data back to the user for browsing of the device.

Session technology is a server-side technology that writes user data to an exclusive Session object created by the server for the user, but Session is based on Cookie.

Session objects are created by the server, which is different from Cookies. Programmers can obtain the Session object through the getSession() method of the request object.

Note that once the Session is created, it will survive no operation (or the browser is closed) for 30 minutes, which is specified by the server (such as Tomcat). When we close the browser, because the Session is based on cookies, the Session still exists, but we may no longer be able to use it (it depends on whether the cookie can still be retrieved).

Then we use a simple Session example to illustrate and create two Servlets: named ServletDemo1 and ServletDemo2 respectively.

The code in ServletDemo1 is as follows:


 HttpSession session = request.getSession();
 String data = "message form SessionDemo";
 session.setAttribute("data", data);
Copy after login

The code in ServletDemo2 is as follows:


 response.setContentType("text/html;charset=utf-8");
 PrintWriter writer = response.getWriter();
     
 HttpSession session = request.getSession();
 String data = (String) session.getAttribute("data");
 writer.write(data);
Copy after login

When we open a browser and visit ServletDemo1 first, the browser will help us create a Session object and save the data. Then we can see the saved data by visiting ServletDemo2:

#Indicates that Session can indeed save data when accessing different Servlets.

Let’s be clear here. Although the codes are the same, if you access them from different browsers, you will see different data saved by different Session objects. Although the data are all different at this time, it's the same. For example, if A accesses this Servlet on his own host and B accesses the same Servlet on his own computer, A and B will get their own Sessions.

And if we open a browser to access ServletDemo1 and then open another browser to access ServletDemo2, it will display that the data cannot be found:

Note: There are two browsers at this time, that is, there are already two sessions! ! !

Let’s do a case similar to clicking on a product and adding it to the shopping cart, using Session technology.

Preliminary preparation, we need to create a JavaBean for the product, the code is as follows:


 public class Product {
   private String id;
   private String name;
   private String author;
  
   public Product() {
     super();
   }
 
   public Product(String id, String name, String author) {
     super();
     this.id = id;
     this.name = name;
     this.author = author;
   }
 
   public String getId() {
     return id;
   }
 
   public void setId(String id) {
     this.id = id;
   }
 
   public String getName() {
     return name;
   }
 
   public void setName(String name) {
     this.name = name;
   }
 
   public String getAuthor() {
     return author;
   }
 
   public void setAuthor(String author) {
     this.author = author;
   }
Copy after login

Then create a database and create it in the form of a class (Who hasn’t learned about databases yet? T_T!), and then use Map collections to store data for easy retrieval through key-value pairs:


 public class ProductDatabase {
   
   private static Map<String,Product> map = new HashMap<String,Product>();
   
   static{
     map.put("1", new Product("1","《Java编程思想》","JB"));
     map.put("2", new Product("2","《Java核心技术》","fdaf"));
     map.put("3", new Product("3","《Java并发编程》","什么鬼"));
     map.put("4", new Product("4","《Head first 设计模式》","老王"));
     map.put("5", new Product("5","《HTML5权威手册》","hhaa"));
   }
   
   public static Map<String,Product> getMap() {
     
     return map;
   }
 }
Copy after login

Okay, let’s display the product Display products on the home page, and create a hyperlink for each product so that when the user clicks the hyperlink, the product ID can be used as the basis for storing data, and other Servlet classes can obtain the type of product purchased by the user:


   response.setCharacterEncoding("UTF-8");
   response.setContentType("text/html;charset=utf-8");
   PrintWriter writer = response.getWriter();
     
   //获取数据库中的商品数据
   Map<String, Product> map = ProductDatabase.getMap();
   for(Map.Entry<String, Product> entry : map.entrySet()) {
     Product book = entry.getValue();
     writer.print(book.getName()+" <a href=&#39;/myservlet/servlet/BuySession?id="+book.getId()+"&#39; >购买</a> <br/>");
     }
Copy after login

You can take a look at the effect at this time:

Then let’s do the Servlet after clicking the purchase hyperlink. The Servlet We need to obtain the goods purchased by the user (through the ID number), and at the same time we need to obtain (create) the Session object, and use a collection to store the purchased goods. This Session object stores the goods the user wishes to purchase. When we jump to When the shopping cart page is on, the product can be taken out from the Session and displayed:


     //获取用户所购买商品的id号
     String productId = request.getParameter("id");
     Product book =   ProductDatabase.getMap().get(productId);
     
     //将用户所购买的商品加入到Session对象中保存,以便最后一起结账,类似于购物车功能
     HttpSession session = request.getSession();
     List<Product> list = (List<Product>) session.getAttribute("productList");
     if(list == null){
       //首次购买
       list = new ArrayList<Product>();
       session.setAttribute("productList", list);
     }
     
     list.add(book);
     
     //跳转到购物车列表上
     response.sendRedirect("/myservlet/servlet/CartListServlet");
Copy after login

Note: sendRedirect redirection is used here. If forward forwarding is used, the product will be displayed during shopping. If the cart page is refreshed, each purchased product will be purchased again.

The function in the Servlet of the shopping cart page can be relatively simple. Take out the saved purchase object from the user's Session and display it on the page:


     response.setCharacterEncoding("UTF-8");
     response.setContentType("text/html;charset=utf-8");
     PrintWriter writer = response.getWriter();
     
     writer.print("您购买的商品如下:  <br/>");
     
     HttpSession session = request.getSession();
     List<Product> list = (List<Product>) session.getAttribute("productList");
     for(Product p : list) {
       writer.write(p.getName()+"<br/>");
     }
Copy after login

Click on multiple products and you will see the products we purchased displayed on the Servlet page of the shopping cart:

If you click on these products in multiple browsers that are opened, you will see different shopping cart pages for purchase, so you can use Session to solve the needs of different users to access the same page while saving their different data.

Of course this is just a simple emphasis that the session object can save the data generated by a browser accessing multiple Servlets during a session. The simple example above cannot be used for shopping. , for example, when we close the browser (the session ends), the session object ends. Then next time we open the browser, our shopping cart will have nothing. If we want to meet the different needs of users, we need to understand some session objects. The underlying structure

The above is the detailed content of Introduction to graphic code of servlet session in Java. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template