/
SessionUtils.java
64 lines (57 loc) · 2 KB
/
SessionUtils.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.auth0;
import org.apache.commons.lang3.Validate;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
/**
* Helper class to handle easy session key-value storage.
*/
@SuppressWarnings({"WeakerAccess", "unused"})
public abstract class SessionUtils {
/**
* Extracts the HttpSession from the given request.
*
* @param req a valid request to get the session from
* @return the session of the request
*/
protected static HttpSession getSession(HttpServletRequest req) {
return req.getSession(true);
}
/**
* Set's the attribute value to the request session.
*
* @param req a valid request to get the session from
* @param name the name of the attribute
* @param value the value to set
*/
public static void set(HttpServletRequest req, String name, Object value) {
Validate.notNull(req);
Validate.notNull(name);
getSession(req).setAttribute(name, value);
}
/**
* Get the attribute with the given name from the request session.
*
* @param req a valid request to get the session from
* @param name the name of the attribute
* @return the attribute stored in the session or null if it doesn't exists
*/
public static Object get(HttpServletRequest req, String name) {
Validate.notNull(req);
Validate.notNull(name);
return getSession(req).getAttribute(name);
}
/**
* Same as {@link #get(HttpServletRequest, String)} but it also removes the value from the request session.
*
* @param req a valid request to get the session from
* @param name the name of the attribute
* @return the attribute stored in the session or null if it doesn't exists
*/
public static Object remove(HttpServletRequest req, String name) {
Validate.notNull(req);
Validate.notNull(name);
Object value = get(req, name);
getSession(req).removeAttribute(name);
return value;
}
}