下面列出了javax.servlet.http.HttpSession#getAttributeNames() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
HttpSession session = req.getSession();
if (req.getParameter("key") != null) {
session.setAttribute(req.getParameter("key"), req.getParameter("value"));
setNonSerializableValues(session);
}
PrintWriter writer = resp.getWriter();
resp.setStatus(HttpServletResponse.SC_OK);
resp.setContentType("text/plain");
Enumeration<?> names = session.getAttributeNames();
if (names.hasMoreElements()) {
while (names.hasMoreElements()) {
String name = (String) names.nextElement();
writer.println(name + ": " + session.getAttribute(name));
}
} else {
writer.println("No session attributes defined.");
}
}
@Override
public Enumeration<String> getAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return getAttributeNames();
case REQUEST_SCOPE:
return this.request.getAttributeNames();
case SESSION_SCOPE:
HttpSession session = this.request.getSession(false);
return (session != null ? session.getAttributeNames() : Collections.emptyEnumeration());
case APPLICATION_SCOPE:
return this.servletContext.getAttributeNames();
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
/**
* Returns all session attributes in a map.
*
* @return all session attributes in a map.
*/
static Map<String, Object> getSessionAttributes(){
try{
HttpSession session = RequestContext.getHttpRequest().getSession(true);
Enumeration names = session.getAttributeNames();
Map<String, Object> values = new HashMap<>();
while (names.hasMoreElements()) {
Object name = names.nextElement();
values.put(name.toString(), session.getAttribute(name.toString()));
}
return values;
}catch (IllegalStateException ex){
// there is a possibility that the controller or filter wrote response back directly,
// which will invalidate the session, so we need to protect from that.
return new HashMap<>();
}
}
/**
* storeSessionAttributes() puts all of the attributes that are available from session.getAttribute()
* into the sessionMap which will be stored in the cluster
* @param s Session that is being stored
* @param sessionMap the Map that will contain the attributes that will eventually stored in the cluster
*/
private void storeSessionAttributes(HttpSession s, Map<String, Serializable> sessionMap) {
@SuppressWarnings("unchecked")
Enumeration<String> keys = s.getAttributeNames();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
if (sessionAttributeBlacklist.contains(key)) {
// skip processing on this key
continue;
}
if (log.isDebugEnabled()) log.debug("attempting to store session attribute key [" + key + "] in cache");
Object object = s.getAttribute(key);
Serializable toStore = serializeSessionAttribute(object);
// now store it if we were successful
if (toStore != null) {
sessionMap.put(key, toStore);
if (log.isDebugEnabled()) log.debug("RebuildBreakdownServiceImpl.storeSession, putting key [" + key + "], class: [" + object.getClass().getName() + "], value: [" + object + "]");
}
}
}
/**
* Retrieves all {@link VaadinSession}s which are stored in the given HTTP
* session.
*
* @param httpSession
* the HTTP session
* @return the found VaadinSessions
*/
public static Collection<VaadinSession> getAllSessions(
HttpSession httpSession) {
Set<VaadinSession> sessions = new HashSet<>();
Enumeration<String> attributeNames = httpSession.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
if (attributeName.startsWith(VaadinSession.class.getName() + ".")) {
Object value = httpSession.getAttribute(attributeName);
if (value instanceof VaadinSession) {
sessions.add((VaadinSession) value);
}
}
}
return sessions;
}
@Override
public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response,
WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
HttpSession session = getSession(request);
if (session != null) {
if (isCopyHttpSessionId()) {
attributes.put(HTTP_SESSION_ID_ATTR_NAME, session.getId());
}
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (isCopyAllAttributes() || getAttributeNames().contains(name)) {
attributes.put(name, session.getAttribute(name));
}
}
}
return true;
}
@Override
public Enumeration<String> getAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return getAttributeNames();
case REQUEST_SCOPE:
return this.request.getAttributeNames();
case SESSION_SCOPE:
HttpSession session = this.request.getSession(false);
return (session != null ? session.getAttributeNames() : null);
case APPLICATION_SCOPE:
return this.servletContext.getAttributeNames();
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
@Override
public Enumeration<String> getAttributeNamesInScope(int scope) {
switch (scope) {
case PAGE_SCOPE:
return getAttributeNames();
case REQUEST_SCOPE:
return this.request.getAttributeNames();
case SESSION_SCOPE:
HttpSession session = this.request.getSession(false);
return (session != null ? session.getAttributeNames() : null);
case APPLICATION_SCOPE:
return this.servletContext.getAttributeNames();
default:
throw new IllegalArgumentException("Invalid scope: " + scope);
}
}
private void reSetAttributes(SessionWrapper sessionWrapper) {
HttpSession realSession = sessionWrapper.delegate;
Enumeration<String> attributeNames = realSession.getAttributeNames();
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
if (!sessionWrapper.readAttributeNames.contains(attributeName)) {
//Attribute was not read, so we don't need to re-set it.
continue;
}
Object attributeValue = realSession.getAttribute(attributeName);
if (ClassUtils.isPrimitiveOrWrapper(attributeValue.getClass())) {
//Attribute is primitive (immutable), so we don't need to re-set it.
continue;
}
realSession.setAttribute(attributeName, attributeValue);
}
}
/** sessionKeys */
public static List<String> sessionKeys() {
HttpSession httpSession = FxWebInterceptor.servletSession();
if (httpSession == null) {
return Collections.emptyList();
}
Enumeration<String> attributeNames = httpSession.getAttributeNames();
List<String> names = new ArrayList<>();
while (attributeNames.hasMoreElements()) {
names.add(attributeNames.nextElement());
}
return names;
}
protected List<String> extractHttpAttributeNameList() { // native only
final HttpSession session = getSessionExisting();
if (session == null) {
return Collections.emptyList();
}
final Enumeration<String> attributeNames = session.getAttributeNames();
final List<String> nameList = new ArrayList<String>();
while (attributeNames.hasMoreElements()) {
nameList.add((String) attributeNames.nextElement());
}
return Collections.unmodifiableList(nameList);
}
/**
* 自运营登录
* @param ah
* @param uuid
* @param uname 名称
* @param uhead 头像
* @return
* @throws HongsException
*/
public static Map userSign(ActionHelper ah, String uuid, String uname, String uhead)
throws HongsException {
long time = System.currentTimeMillis() / 1000 ;
HttpSession sd = ah.getRequest( ).getSession(false);
// 重建会话
if (sd != null) {
Enumeration<String> ns = sd.getAttributeNames();
Map<String, Object> ss = new HashMap (/*Copy*/);
while ( ns.hasMoreElements() ) {
String nn = ns.nextElement ( );
ss.put(nn , sd.getAttribute(nn) );
}
sd.invalidate();
sd = ah.getRequest().getSession(true);
for(Map.Entry<String,Object> et: ss.entrySet()) {
sd.setAttribute(et.getKey(), et.getValue());
}
} else {
sd = ah.getRequest().getSession(true);
}
String ssid = sd.getId();
// 设置会话
sd.setAttribute(Cnst.UID_SES, uuid);
sd.setAttribute(Cnst.UST_SES, time);
sd.setAttribute(NAME, uname);
sd.setAttribute(HEAD, uhead);
// 返回数据
Map rd = new HashMap();
rd.put(Cnst.UST_SES, time);
rd.put(Cnst.UID_SES, uuid);
rd.put(SSID, ssid );
rd.put(NAME, uname);
rd.put(HEAD, uhead);
return rd;
}
/** 删除所有Key */
public static boolean cleanSession() {
HttpSession httpSession = FxWebInterceptor.servletSession();
if (httpSession == null) {
return false;
}
Enumeration<String> attributeNames = httpSession.getAttributeNames();
while (attributeNames.hasMoreElements()) {
httpSession.removeAttribute(attributeNames.nextElement());
}
return true;
}
protected static Map<ParticipantId, SessionUser> readAllSessionUser(HttpSession session) {
Map<ParticipantId, SessionUser> map = new HashMap<ParticipantId, SessionUser>();
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
if (!name.equals(OLD_USER_ID_ATTR))
map.put(ParticipantId.ofUnsafe(name), (SessionUser) session.getAttribute(name));
}
return map;
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE html><html>");
out.println("<head>");
out.println("<meta charset=\"UTF-8\" />");
String title = RB.getString("sessions.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// img stuff not req'd for source code html showing
// relative links everywhere!
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../sessions.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
HttpSession session = request.getSession(true);
out.println(RB.getString("sessions.id") + " " + session.getId());
out.println("<br>");
out.println(RB.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "<br>");
out.println(RB.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()));
String dataName = request.getParameter("dataname");
String dataValue = request.getParameter("datavalue");
if (dataName != null && dataValue != null) {
session.setAttribute(dataName, dataValue);
}
out.println("<P>");
out.println(RB.getString("sessions.data") + "<br>");
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = session.getAttribute(name).toString();
out.println(HTMLFilter.filter(name) + " = "
+ HTMLFilter.filter(value) + "<br>");
}
out.println("<P>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=POST>");
out.println(RB.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(RB.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.println("<P>GET based form:<br>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=GET>");
out.println(RB.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(RB.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.print("<p><a href=\"");
out.print(HTMLFilter.filter(response.encodeURL("SessionExample?dataname=foo&datavalue=bar")));
out.println("\" >URL encoded </a>");
out.println("</body>");
out.println("</html>");
}
protected Iterator<String> getAttributeNames() {
HttpSession session = getSession();
return (session != null) ? new EnumerationIterator<String>(session.getAttributeNames()) : EMPTY_ITERATOR;
}
/**
* Returns the portlet session.
* <p>
* Note that since portlet request instance is created everytime the portlet
* container receives an incoming request, the portlet session instance held
* by the request instance is also re-created for each incoming request.
* </p>
*/
@Override
public PortletSession getPortletSession(boolean create) {
if (isDebug) {
LOG.debug("Retrieving portlet session (create=" + create + ")");
}
if ((cachedPortletSession == null) || cachedPortletSession.isInvalidated()) {
//
// It is critical that we don't retrieve the portlet session until the
// cross context dispatch has been completed. If we do then we risk
// having a cached version which is invalid for the context within
// which it exists.
//
if (portletConfig == null) {
throw new IllegalStateException(EXCEPTIONS.getString("error.session.illegalState"));
}
//
// We must make sure that if the session has been invalidated (perhaps
// through setMaxIntervalTimeout()) and the underlying request
// returns null that we no longer use the cached version.
// We have to check (ourselves) if the session has exceeded its max
// inactive interval. If so, we should invalidate the underlying
// HttpSession and recreate a new one (if the create flag is set to
// true) -- We just cannot depend on the implementation of
// javax.servlet.http.HttpSession!
//
HttpSession httpSession = getServletRequest().getSession(create);
if (httpSession != null) {
// HttpSession is not null does NOT mean that it is valid.
int maxInactiveInterval = httpSession.getMaxInactiveInterval();
long lastAccesstime = httpSession.getLastAccessedTime();// lastAccesstime checks added for PLUTO-436
if (maxInactiveInterval >= 0 && lastAccesstime > 0) { // < 0 => Never expires.
long maxInactiveTime = httpSession.getMaxInactiveInterval() * 1000L;
long currentInactiveTime = System.currentTimeMillis() - lastAccesstime;
if (currentInactiveTime > maxInactiveTime) {
if (isDebug) {
LOG.debug("The underlying HttpSession is expired and " + "should be invalidated.");
}
httpSession.invalidate();
httpSession = getServletRequest().getSession(create);
// Added for PLUTO-436
// a cached portletSession is no longer useable.
// a new one will be created below.
}
}
}
if (httpSession == null) {
if (isDebug) {
LOG.debug("The underlying HttpSession is not available: " + "no session will be returned.");
}
return null;
}
//
// If we reach here, we are sure that the underlying HttpSession is
// available. If we haven't created and cached a portlet session
// instance, we will create and cache one now.
//
final ContainerServices containerServices = container.getContainerServices();
final PortletEnvironmentService portletEnvironmentService = containerServices.getPortletEnvironmentService();
cachedPortletSession = new CachedPortletSessionImpl(portletEnvironmentService.createPortletSession(
portletConfig.getPortletContext(), getPortletWindow(), httpSession));
if (CachedPortletSessionUtil.INVALIDATED_SESSIONS.containsKey(httpSession.getId())) {
synchronized (httpSession) {
Enumeration<String> attributeNames = httpSession.getAttributeNames();
if (attributeNames.hasMoreElements()) {
while (attributeNames.hasMoreElements()) {
String attributeName = attributeNames.nextElement();
httpSession.removeAttribute(attributeName);
}
CachedPortletSessionUtil.INVALIDATED_SESSIONS.remove(httpSession.getId());
}
}
}
}
return cachedPortletSession;
}
@Override
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
String title = RB.getString("sessions.title");
out.println("<title>" + title + "</title>");
out.println("</head>");
out.println("<body bgcolor=\"white\">");
// img stuff not req'd for source code html showing
// relative links everywhere!
// XXX
// making these absolute till we work out the
// addition of a PathInfo issue
out.println("<a href=\"../sessions.html\">");
out.println("<img src=\"../images/code.gif\" height=24 " +
"width=24 align=right border=0 alt=\"view code\"></a>");
out.println("<a href=\"../index.html\">");
out.println("<img src=\"../images/return.gif\" height=24 " +
"width=24 align=right border=0 alt=\"return\"></a>");
out.println("<h3>" + title + "</h3>");
HttpSession session = request.getSession(true);
out.println(RB.getString("sessions.id") + " " + session.getId());
out.println("<br>");
out.println(RB.getString("sessions.created") + " ");
out.println(new Date(session.getCreationTime()) + "<br>");
out.println(RB.getString("sessions.lastaccessed") + " ");
out.println(new Date(session.getLastAccessedTime()));
String dataName = request.getParameter("dataname");
String dataValue = request.getParameter("datavalue");
if (dataName != null && dataValue != null) {
session.setAttribute(dataName, dataValue);
}
out.println("<P>");
out.println(RB.getString("sessions.data") + "<br>");
Enumeration<String> names = session.getAttributeNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = session.getAttribute(name).toString();
out.println(HTMLFilter.filter(name) + " = "
+ HTMLFilter.filter(value) + "<br>");
}
out.println("<P>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=POST>");
out.println(RB.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(RB.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.println("<P>GET based form:<br>");
out.print("<form action=\"");
out.print(response.encodeURL("SessionExample"));
out.print("\" ");
out.println("method=GET>");
out.println(RB.getString("sessions.dataname"));
out.println("<input type=text size=20 name=dataname>");
out.println("<br>");
out.println(RB.getString("sessions.datavalue"));
out.println("<input type=text size=20 name=datavalue>");
out.println("<br>");
out.println("<input type=submit>");
out.println("</form>");
out.print("<p><a href=\"");
out.print(HTMLFilter.filter(response.encodeURL("SessionExample?dataname=foo&datavalue=bar")));
out.println("\" >URL encoded </a>");
out.println("</body>");
out.println("</html>");
}
@ApiOperation("获取Session中的值")
@RequestMapping(value = "/session/get", method = RequestMethod.GET)
public Map<String, Object> get(HttpSession session) {
/**
*
{
"org.springframework.security.web.csrf.HttpSessionCsrfTokenRepository.CSRF_TOKEN": {
"headerName": "X-CSRF-TOKEN",
"parameterName": "_csrf",
"token": "b409d267-2f7f-4b48-ab7c-4aa50dfcdfe3"
},
"KAPTCHA_SESSION_KEY": "2a3y",
"SPRING_SECURITY_CONTEXT": {
"authentication": {
"authenticated": true,
"authorities": [
{
"authority": "ROLE_ADMIN"
}
],
"credentials": "",
"details": {
"remoteAddress": "0:0:0:0:0:0:0:1",
"sessionId": "5b0f7167-a187-4323-8642-74f76542a5c7"
},
"name": "admin",
"principal": {
"accountNonExpired": true,
"accountNonLocked": true,
"authorities": [
{
"$ref": "$.SPRING_SECURITY_CONTEXT.authentication.authorities[0]"
}
],
"credentialsNonExpired": true,
"enabled": true,
"password": "",
"username": "admin"
}
}
}
}
*/
Map<String, Object> sessionMap = new HashMap<>();
// 获取session中所有的键值
Enumeration<String> enumeration = session.getAttributeNames();
// 遍历enumeration中的
while (enumeration.hasMoreElements()) {
// 获取session键值
String name = enumeration.nextElement();
sessionMap.put(name, session.getAttribute(name));
}
return sessionMap;
}
private ResponseObject createLoginResponse(final HttpSession session) {
final LoginCmdResponse response = new LoginCmdResponse();
response.setTimeout(session.getMaxInactiveInterval());
final String user_UUID = (String) session.getAttribute("user_UUID");
response.setUserId(user_UUID);
final String domain_UUID = (String) session.getAttribute("domain_UUID");
response.setDomainId(domain_UUID);
synchronized (session) {
session.removeAttribute("user_UUID");
session.removeAttribute("domain_UUID");
}
final Enumeration attrNames = session.getAttributeNames();
if (attrNames != null) {
while (attrNames.hasMoreElements()) {
final String attrName = (String) attrNames.nextElement();
final Object attrObj = session.getAttribute(attrName);
if (ApiConstants.USERNAME.equalsIgnoreCase(attrName)) {
response.setUsername(attrObj.toString());
}
if (ApiConstants.ACCOUNT.equalsIgnoreCase(attrName)) {
response.setAccount(attrObj.toString());
}
if (ApiConstants.FIRSTNAME.equalsIgnoreCase(attrName)) {
response.setFirstName(attrObj.toString());
}
if (ApiConstants.LASTNAME.equalsIgnoreCase(attrName)) {
response.setLastName(attrObj.toString());
}
if (ApiConstants.TYPE.equalsIgnoreCase(attrName)) {
response.setType((attrObj.toString()));
}
if (ApiConstants.TIMEZONE.equalsIgnoreCase(attrName)) {
response.setTimeZone(attrObj.toString());
}
if (ApiConstants.REGISTERED.equalsIgnoreCase(attrName)) {
response.setRegistered(attrObj.toString());
}
if (ApiConstants.SESSIONKEY.equalsIgnoreCase(attrName)) {
response.setSessionKey(attrObj.toString());
}
if (ApiConstants.DOMAIN_NAME.equalsIgnoreCase(attrName)) {
response.setDomainName(attrObj.toString());
}
}
}
response.setResponseName("loginresponse");
return response;
}