本文整理了Java中javax.servlet.http.HttpSession.setAttribute()
方法的一些代码示例,展示了HttpSession.setAttribute()
的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。HttpSession.setAttribute()
方法的具体详情如下:
包路径:javax.servlet.http.HttpSession
类名称:HttpSession
方法名:setAttribute
[英]Binds an object to this session, using the name specified. If an object of the same name is already bound to the session, the object is replaced.
After this method executes, and if the new object implements HttpSessionBindingListener
, the container calls HttpSessionBindingListener.valueBound
. The container then notifies any HttpSessionAttributeListener
s in the web application.
If an object was already bound to this session of this name that implements HttpSessionBindingListener
, its HttpSessionBindingListener.valueUnbound
method is called.
If the value passed in is null, this has the same effect as calling removeAttribute()
.
[中]使用指定的名称将对象绑定到此会话。如果同名对象已绑定到会话,则该对象将被替换。
执行此方法后,如果新对象实现HttpSessionBindingListener
,容器将调用HttpSessionBindingListener.valueBound
。然后容器通知web应用程序中的任何HttpSessionAttributeListener
。
如果对象已绑定到此实现HttpSessionBindingListener
的同名会话,则调用其HttpSessionBindingListener.valueUnbound
方法。
如果传入的值为null,则这与调用removeAttribute()
具有相同的效果。
代码示例来源:origin: gocd/gocd
public static void saveRequest(HttpServletRequest request, SavedRequest savedRequest) {
request.getSession().setAttribute(SAVED_REQUEST, savedRequest);
}
代码示例来源:origin: stackoverflow.com
HttpSession session = request.getSession();
Integer n = (Integer) session.getAttribute("foo");
// not thread safe
// another thread might be have got stale value between get and set
session.setAttribute("foo", (n == null) ? 1 : n + 1);
代码示例来源:origin: spring-projects/spring-framework
/**
* Set the session attribute with the given name to the given value.
* Removes the session attribute if value is null, if a session existed at all.
* Does not create a new session if not necessary!
* @param request current HTTP request
* @param name the name of the session attribute
* @param value the value of the session attribute
*/
public static void setSessionAttribute(HttpServletRequest request, String name, @Nullable Object value) {
Assert.notNull(request, "Request must not be null");
if (value != null) {
request.getSession().setAttribute(name, value);
}
else {
HttpSession session = request.getSession(false);
if (session != null) {
session.removeAttribute(name);
}
}
}
代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server
/**
* Set the timestamp on the session to mark when the authentication happened,
* useful for calculating authentication age. This gets stored in the sesion
* and can get pulled out by other components.
*/
@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
Date authTimestamp = new Date();
HttpSession session = request.getSession();
session.setAttribute(AUTH_TIMESTAMP, authTimestamp);
if (session.getAttribute(AuthorizationRequestFilter.PROMPT_REQUESTED) != null) {
session.setAttribute(AuthorizationRequestFilter.PROMPTED, Boolean.TRUE);
session.removeAttribute(AuthorizationRequestFilter.PROMPT_REQUESTED);
}
logger.info("Successful Authentication of " + authentication.getName() + " at " + authTimestamp.toString());
super.onAuthenticationSuccess(request, response, authentication);
}
代码示例来源:origin: stackoverflow.com
HttpServletRequest request = this.getThreadLocalRequest();
HttpSession session = request.getSession();
// in your authentication method
if(isCorrectPassword)
session.setAttribute("authenticatedUserName", "name");
// later
if (session.getAttribute("authenticatedUserName") != null)
代码示例来源:origin: alibaba/druid
String usernameParam = request.getParameter(PARAM_NAME_USERNAME);
String passwordParam = request.getParameter(PARAM_NAME_PASSWORD);
if (username.equals(usernameParam) && password.equals(passwordParam)) {
request.getSession().setAttribute(SESSION_USER_KEY, username);
response.getWriter().print("success");
} else {
|| path.startsWith("/img"))) {
if (contextPath.equals("") || contextPath.equals("/")) {
response.sendRedirect("/druid/login.html");
} else {
if ("".equals(path)) {
response.sendRedirect("druid/login.html");
} else {
response.sendRedirect("login.html");
代码示例来源:origin: ZHENFENG13/My-Blog
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
String contextPath = request.getContextPath();
// System.out.println(contextPath);
String uri = request.getRequestURI();
LOGGE.info("UserAgent: {}", request.getHeader(USER_AGENT));
LOGGE.info("用户访问地址: {}, 来路地址: {}", uri, IPKit.getIpAddrByRequest(request));
//请求拦截处理
UserVo user = TaleUtils.getLoginUser(request);
if (null == user) {
Integer uid = TaleUtils.getCookieUid(request);
if (null != uid) {
//这里还是有安全隐患,cookie是可以伪造的
user = userService.queryUserById(uid);
request.getSession().setAttribute(WebConst.LOGIN_SESSION_KEY, user);
}
}
if (uri.startsWith(contextPath + "/admin") && !uri.startsWith(contextPath + "/admin/login") && null == user) {
response.sendRedirect(request.getContextPath() + "/admin/login");
return false;
}
//设置get请求的token
if (request.getMethod().equals("GET")) {
String csrf_token = UUID.UU64();
// 默认存储30分钟
cache.hset(Types.CSRF_TOKEN.getType(), csrf_token, uri, 30 * 60);
request.setAttribute("_csrf_token", csrf_token);
}
return true;
}
代码示例来源:origin: DeemOpen/zkui
uploadFileName = scmServer + scmFileRevision + "@" + scmFilePath;
logger.debug("P4 file Processing " + uploadFileName);
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Importing P4 File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
URL url = new URL(uploadFileName);
URLConnection conn = url.openConnection();
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Uploading File: " + uploadFileName + "<br/>" + "Overwrite: " + scmOverwrite);
inpStream = new ByteArrayInputStream(sbFile.toString().getBytes());
for (String line : importFile) {
if (line.startsWith("-")) {
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Deleting Entry: " + line);
} else {
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "File: " + uploadFileName + ", Adding Entry: " + line);
request.getSession().setAttribute("flashMsg", "Import Completed!");
response.sendRedirect("/home");
} catch (FileUploadException | IOException | InterruptedException | KeeperException ex) {
logger.error(Arrays.toString(ex.getStackTrace()));
代码示例来源:origin: DeemOpen/zkui
String action = request.getParameter("action");
String currentPath = request.getParameter("currentPath");
String displayPath = request.getParameter("displayPath");
String authRole = (String) request.getSession().getAttribute("authRole");
request.getSession().setAttribute("flashMsg", "Node created!");
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Creating node: " + currentPath + newNode);
request.getSession().setAttribute("flashMsg", "Property Saved!");
if (ZooKeeperUtil.INSTANCE.checkIfPwdField(newProperty)) {
newValue = ZooKeeperUtil.INSTANCE.SOPA_PIPA;
dao.insertHistory((String) request.getSession().getAttribute("authName"), request.getRemoteAddr(), "Saving Property: " + currentPath + "," + newProperty + "=" + newValue);
request.getSession().setAttribute("flashMsg", "Property Updated!");
if (ZooKeeperUtil.INSTANCE.checkIfPwdField(newProperty)) {
newValue = ZooKeeperUtil.INSTANCE.SOPA_PIPA;
List delPropLst = Arrays.asList(prop);
ZooKeeperUtil.INSTANCE.deleteLeaves(delPropLst, ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps));
request.getSession().setAttribute("flashMsg", "Delete Completed!");
List delNodeLst = Arrays.asList(node);
ZooKeeperUtil.INSTANCE.deleteFolders(delNodeLst, ServletUtil.INSTANCE.getZookeeper(request, response, zkServerLst[0], globalProps));
request.getSession().setAttribute("flashMsg", "Delete Completed!");
代码示例来源:origin: jenkinsci/jenkins
/**
* @see org.acegisecurity.ui.AbstractProcessingFilter#determineFailureUrl(javax.servlet.http.HttpServletRequest, org.acegisecurity.AuthenticationException)
*/
@Override
protected String determineFailureUrl(HttpServletRequest request, AuthenticationException failed) {
Properties excMap = getExceptionMappings();
String failedClassName = failed.getClass().getName();
String whereFrom = request.getParameter("from");
request.getSession().setAttribute("from", whereFrom);
return excMap.getProperty(failedClassName, getAuthenticationFailureUrl());
}
代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server
HttpSession session = request.getSession();
session.setAttribute(LOGIN_HINT, loginHint);
} else {
session.removeAttribute(LOGIN_HINT);
response.sendRedirect(uriBuilder.toString());
return;
if (session.getAttribute(PROMPTED) == null) {
session.setAttribute(PROMPT_REQUESTED, Boolean.TRUE);
session.removeAttribute(PROMPTED);
chain.doFilter(req, res);
Date authTime = (Date) session.getAttribute(AuthenticationTimeStamper.AUTH_TIMESTAMP);
代码示例来源:origin: spring-projects/spring-session
@Override
public void doFilter(HttpServletRequest wrappedRequest) {
wrappedRequest.getSession().setAttribute(ATTR, VALUE);
assertThat(wrappedRequest.getSession().getAttribute(ATTR))
.isEqualTo(VALUE);
assertThat(
Collections.list(wrappedRequest.getSession().getAttributeNames()))
.containsOnly(ATTR);
}
});
代码示例来源:origin: jenkinsci/jenkins
@Override
public boolean toggleCollapsed(String paneId) {
final HttpSession session = Stapler.getCurrentRequest().getSession();
final String property = format(attribute, paneId);
final Object collapsed = session.getAttribute(property);
if (collapsed == null) {
session.setAttribute(property, true);
return true;
}
session.removeAttribute(property);
return false;
}
}
代码示例来源:origin: Red5/red5-server
/** {@inheritDoc} */
public boolean setAttribute(String name, Object value) {
if (name == null) {
return false;
}
if (value == null) {
session.removeAttribute(name);
} else {
session.setAttribute(name, value);
}
return true;
}
代码示例来源:origin: spring-projects/spring-framework
while (attrNames.hasMoreElements()) {
String attrName = attrNames.nextElement();
Object attrValue = parentSession.getAttribute(attrName);
localSession.setAttribute(attrName, attrValue);
代码示例来源:origin: apache/cloudstack
s_logger.debug("Sending SAMLRequest id=" + authnId);
String redirectUrl = SAMLUtils.buildAuthnRequestUrl(authnId, spMetadata, idpMetadata, SAML2AuthManager.SAMLSignatureAlgorithm.value());
resp.sendRedirect(redirectUrl);
return "";
} if (params.containsKey("SAMLart")) {
session.setAttribute(SAMLPluginConstants.SAML_IDPID, issuer.getValue());
session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
break;
session.setAttribute(SAMLPluginConstants.SAML_NAMEID, assertion.getSubject().getNameID().getValue());
userAccount.getDomainId(), null, remoteAddress, params);
SAMLUtils.setupSamlUserCookies(loginResponse, resp);
resp.sendRedirect(SAML2AuthManager.SAMLCloudStackRedirectionUrl.value());
return ApiResponseSerializer.toSerializedString(loginResponse, responseType);
代码示例来源:origin: BroadleafCommerce/BroadleafCommerce
private Long lookupSandboxId(HttpServletRequest request) {
String sandboxIdStr = request.getParameter(SANDBOX_ID_VAR);
Long sandboxId = null;
if (sandboxIdStr != null) {
try {
sandboxId = Long.valueOf(sandboxIdStr);
if (LOG.isTraceEnabled()) {
LOG.trace("SandboxId found on request " + sandboxId);
}
} catch (NumberFormatException nfe) {
LOG.warn("blcSandboxId parameter could not be converted into a Long", nfe);
}
}
if (sandboxId == null) {
// check the session
HttpSession session = request.getSession(false);
if (session != null) {
sandboxId = (Long) session.getAttribute(SANDBOX_ID_VAR);
if (LOG.isTraceEnabled()) {
if (sandboxId != null) {
LOG.trace("SandboxId found in session " + sandboxId);
}
}
}
} else {
HttpSession session = request.getSession();
session.setAttribute(SANDBOX_ID_VAR, sandboxId);
}
return sandboxId;
}
代码示例来源:origin: azkaban/azkaban
/**
* Adds a session value to the request
*/
protected void addSessionValue(final HttpServletRequest request, final String key,
final Object value) {
List l = (List) request.getSession(true).getAttribute(key);
if (l == null) {
l = new ArrayList();
}
l.add(value);
request.getSession(true).setAttribute(key, l);
}
代码示例来源:origin: jfinal/jfinal
String usernameParam = request.getParameter(PARAM_NAME_USERNAME);
String passwordParam = request.getParameter(PARAM_NAME_PASSWORD);
if (username.equals(usernameParam) && password.equals(passwordParam)) {
request.getSession().setAttribute(SESSION_USER_KEY, username);
response.getWriter().print("success");
} else {
|| path.startsWith("/img"))) {
if (contextPath == null || contextPath.equals("") || contextPath.equals("/")) {
response.sendRedirect("/druid/login.html");
} else {
if ("".equals(path)) {
response.sendRedirect("druid/login.html");
} else {
response.sendRedirect("login.html");
代码示例来源:origin: mitreid-connect/OpenID-Connect-Java-Spring-Server
HttpSession session = request.getSession();
response.sendRedirect(issResp.getRedirectUrl());
} else {
String issuer = issResp.getIssuer();
session.setAttribute(TARGET_SESSION_VARIABLE, issResp.getTargetLinkUri());
session.setAttribute(ISSUER_SESSION_VARIABLE, serverConfig.getIssuer());
session.setAttribute(REDIRECT_URI_SESION_VARIABLE, redirectUri);
response.sendRedirect(authRequest);
内容来源于网络,如有侵权,请联系作者删除!