Introduction to graphic code of servlet session in Java
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);
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);
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; }
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; } }
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='/myservlet/servlet/BuySession?id="+book.getId()+"' >购买</a> <br/>"); }
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");
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/>"); }
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.
