简体   繁体   中英

Best approach to manage a List<String> variable throughout session in Spring MVC

I am using Spring MVC 3.2.4 to design a web based application. As per the requirement, (using Tiles view) Employee Name as hyperlink will be displayed on left side of the web page and on clicking them, right side will display Employee's details. There are other CRUD operations/forms exists like adding a new employee, deleting them and modify records.

Therefore, Employee Name will always be displayed on left side of Tiles view just like a (dynamic) menu. My question is how this List<String> employeeName be managed in Spring so that it should be available throughout a session? Should ModelAttribute, Cookie or anything else be used?

As of now, I have implemented this with @ModelAttribute but List<String> employeeName is being appeared in URL, therefore, I am planning of using Cookies.

Need your kind advise on what should be the best practice/approach for handling such situations?

Thanks in advance

If you want to have List<String> throughout the session then use request.getSession.setAttribute("employees", employeeName);

With this, you can get employee name list anywhere until you invalidate the session.

The easiest way to access session is through HttpSession handler method argument. Set it once

@RequestMapping(value = "/some-url/{someArg}", method = RequestMethod.POST)
public void someMethod(@PathVariable String someArg, HttpSession session) {    
     List<String> employeeName = getEmployees();
     session.setAttribute("employees", employeeName);
}

And then you can use it in other methods:

@RequestMapping(value = "/some-other-url/{someArg}", method = RequestMethod.GET)
public String someOtherMethod(@PathVariable String someArg, HttpSession session) {    
     List<String> employeeName = (List<String>)session.getAttribute("employees");
}

Note: there is significant downsides in the design decision to store employees identifiers in session:

  1. Creation/deletion of employee by one user is not reflected for other users automatically as session is stored per application user.
  2. Creation/deletion of employee requires modification of stored list in session.
  3. Each application user has own session and hence own list of employees stored in session and if the number employees and users is large application would require more memory.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM