JavaWeb: The difference between request.setAttribute() and session.setAttribute()

When writing servlet layer programs in javaweb, in order to achieve front-end and back-end interaction, we usually use request.setAttribute() and session.setAttribute() to save some information for use in other pages or servlets. This article mainly introduces the differences between the two. First, let’s introduce setAttribute().

1. setAttribute() method

Function: Add a new attribute with a specified name and value, or set an existing attribute to a specified value.

Syntax: setAttribute(name, value)

illustrate:

(1) name: the attribute name to be set

(2) value: attribute value to be set

Note: Sets the specified property to the specified value. If a property with the specified name does not exist, this method creates a new property.

二、request.setAttribute()

Function: request.setAttribute() shares data within a request

Explanation: For example, if you save a piece of data in the request field and then forward the request to the front-end page, the data will be automatically destroyed after being forwarded to the front-end page. To put it simply, data can only be used once and then no longer used.

request.setAttribute("login_msg","验证码错误!");
request.getRequestDispatcher("/login.jsp").forward(request,response);

三、session.setAttribute()

Function: session.setAttribute() is to share data between multiple requests in a session

Explanation: If the session.setAttribute() method is used, the data will be saved until the end of the entire session. To put it simply, data can always be used as long as it is not destroyed.

HttpSession session = request.getSession();
session.setAttribute("user",loginUser);
response.sendRedirect(request.getContextPath()+"/index.jsp");

Note: Session data can only be saved for 20 minutes and will be destroyed when the browser is closed.

How to manually destroy Session data? You can take a look at another article:

JavaWeb: The difference between request.getSession().invalidate() and request.getSession().removeAttribute() https://blog.csdn.net/m0_52625549/article/details/124665513?spm=1001.2014.3001.5501

Guess you like

Origin blog.csdn.net/m0_52625549/article/details/124666401