Spring Boot - HttpSession

HttpSession

You can use HttpServletRequest.getSession() method to get the current HttpSession.

Set Session Attribute

Use HttpSession.setAttribute() method to set attribute to the session. The session value can be any Object.

Here is an example to set a session in the controller

1
2
3
4
5
6
@GetMapping("/setValue")
public String setValue(HttpServletRequest request) {
HttpSession session = request.getSession();
session.setAttribute("foo", "bar");
return "OK";
}

WebUtils offers method to set Session attribute.

1
WebUtils.setSessionAttribute(request, "foo", "bar");

Get Session Attribute

Use HttpSession.getAttribute() to get attribute value

1
2
3
4
5
6
7
8
@GetMapping("/getValue")
public String getValue(HttpServletRequest request) {
HttpSession session = request.getSession();
if( session.getAttribute("foo") != null){
LOG.info(session.getAttribute("foo").toString());
}
return "OK";
}

Get Session attribute using WebUtils:

1
WebUtils.getSessionAttribute(request, "foo").toString();

Get All Session Attribute

use Enumeration e = session.getAttributeNames() to get all the session names, then use HttpSession.getAttribute() method to get the session attribute.

1
2
3
4
5
6
7
8
9
10
@GetMapping("/getAll")
public String getAll(HttpServletRequest request) {
HttpSession session = request.getSession();
Enumeration e = session.getAttributeNames();
while(e.hasMoreElements()) {
Object key = e.nextElement();
LOG.info(key.toString() + "=" + session.getAttribute(key.toString()));
}
return "OK";
}