How do you store information in session memory in

2019-09-14 21:30发布

问题:

I have a unique situation in which I want to store an array of integers into memory via a POST. I think want to fetch this data later with a GET request.

This may seem strange, and weird, but I do have a use case, and it will only be in memory for a few seconds.

A simple example -- Store the array someArray = [1, 2, 3]; in some sort of in memory storage with a POST, and retrieve it via GET in another function.

回答1:

Since you will have access to HttpServletRequest in your controller, you just have to invoke getSession method:

HttpSession session = request.getSession(false);

Now you have access to the Session, so you can store, retrieve and remove data from it using the relevant methods:

  • HttpSession#setAttribute
  • HttpSession#getAttribute
  • HttpSession#removeAttribute

As said in comments, you can also omit getting the session manually and send it as parameter to your method from your @Controller. Taken from this answer

@RequestMapping...)
public String processSubmit(..., HttpSession session, ...) {
    Object anAttribute = session.getAttribute("anAttribute");
}


回答2:

I ever had this kind of requirement that first posted main data to controller and then posted some detail data to controller and combine 2 kinds of data and retrieved data from database with these data. I just store the main data in session with session.setAttribute(), Spring mvc has a @SessionAttribute, but after tried dozens of time, I gave up, it's very difficlut to use.