下面列出了javax.servlet.http.HttpSession#getId() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* If the given {@link ServletRequest} is an instance of {@link HttpServletRequest}, this methods extracts the session ID and registers it in the
* {@link #SESSION_REGISTRY} in order to be accessible for other probes in this thread. In case no session is associated with this request (or if the request is
* not an instance of {@link HttpServletRequest}), this method returns without any further actions and returns {@link OperationExecutionRecord#NO_SESSION_ID}.
*
* @param request
* The request.
*
* @return The session ID.
*/
protected String registerSessionInformation(final ServletRequest request) {
String sessionId = OperationExecutionRecord.NO_SESSION_ID;
if ((request == null) || !(request instanceof HttpServletRequest)) {
return sessionId;
}
final HttpSession session = ((HttpServletRequest) request).getSession(false);
if (session != null) {
sessionId = session.getId();
SESSION_REGISTRY.storeThreadLocalSessionId(sessionId);
}
return sessionId;
}
void unregisterInvalidatedSessions() {
for (final Map.Entry<String, HttpSession> entry : SESSION_MAP_BY_ID.entrySet()) {
final HttpSession session = entry.getValue();
if (session.getId() != null) {
unregisterSessionIfNeeded(session);
} else {
// damned JIRA has sessions with null id, when shuting down
final String sessionId = entry.getKey();
SESSION_MAP_BY_ID.remove(sessionId);
}
}
// issue 198: in JIRA 4.4.*, sessionCreated is called two times with different sessionId
// but with the same attributes in the second than the attributes added in the first,
// so SESSION_COUNT is periodically counted again
SESSION_COUNT.set(SESSION_MAP_BY_ID.size());
}
/**
* Remember with servlets each of these is done on a thread from the
* pool. Therefore it should filter down giving each session its
* own object with which to slice. In this way if a user decides to
* do a long running slice, they only block themselves.
*
* TODO User should be able to cancel slice...
*
*/
private void doHandle(HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
HttpSession sess = request.getSession();
SliceRequest slicer=null;
// Assignment of slicer is synched
synchronized(LOCK) {
slicer = (SliceRequest)sess.getAttribute("slicer");
if (slicer==null) {
slicer = new SliceRequest(sess.getId());
sess.setAttribute("slicer", slicer);
}
}
try {
slicer.slice(request, response);
} catch (Exception ne) {
ne.printStackTrace();
response.setContentType("text/html;charset=utf-8");
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
response.getWriter().println("<h1>"+ne.getMessage()+"</h1>");
}
}
@Override
protected void doGet(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession(true);
String old = session.getId();
req.changeSessionId();
String newId = session.getId();
resp.getWriter().write(old + " "+ newId);
}
/**
* Returns the final response from the servlet. Note that this method should
* only be invoked after all processing has been done to the servlet response.
**/
public WebResponse getServletResponse() throws IOException {
if (_contextStack.size() != 1) throw new IllegalStateException( "Have not returned from all request dispatchers" );
if (_webResponse == null) {
HttpSession session = getRequest().getSession( /* create */ false );
if (session != null && session.isNew()) {
Cookie cookie = new Cookie( ServletUnitHttpSession.SESSION_COOKIE_NAME, session.getId() );
cookie.setPath( _application.getContextPath() );
getResponse().addCookie( cookie );
}
_webResponse = new ServletUnitWebResponse( _client, _frame, _effectiveURL, getResponse(), _client.getExceptionsThrownOnErrorStatus() );
}
return _webResponse;
}
@Override
public void sessionDestroyed(HttpSessionEvent ev) {
HttpSession session = ev.getSession();
String id = session.getId();
sessions.remove(session);
//System.out.println("SESSION: " + id + " was destroyed");
}
@Override
protected String changeHttpSessionId(boolean create) {
Request request = this.request;
HttpSession session = request.getSession(false);
if (session == null) {
return request.getSession(true).getId();
}
if (!deployment.isTurnOffChangeSessionIdOnLogin()) return request.changeSessionId();
else return session.getId();
}
protected String localSessionId(final HttpServletRequest request) {
final String sessionId = Cookies.get(request, sessionIdName);
if(StringUtils.isNotBlank(sessionId)) {
return sessionId;
}
final HttpSession session = request.getSession();
if(session != null) {
return session.getId();
}
throw new NullPointerException("Not found session id.");
}
/**
* Records the access token value and remote address and will also set the session Id if a session
* already exists (it won't create one).
*
* @param request that the authentication request was received from
*/
public CustomOAuth2AuthenticationDetails(HttpServletRequest request) {
this.tokenValue = (String) request.getAttribute(ACCESS_TOKEN_VALUE);
this.tokenType = (String) request.getAttribute(ACCESS_TOKEN_TYPE);
this.remoteAddress = RemoteAddressUtils.getRealIp(request);
HttpSession session = request.getSession(false);
this.sessionId = (session != null) ? session.getId() : null;
StringBuilder builder = new StringBuilder();
if (remoteAddress != null) {
builder.append("remoteAddress=").append(remoteAddress);
}
if (builder.length() > 1) {
builder.append(", ");
}
if (sessionId != null) {
builder.append("sessionId=<SESSION>");
if (builder.length() > 1) {
builder.append(", ");
}
}
if (tokenType != null) {
builder.append("tokenType=").append(this.tokenType);
}
if (tokenValue != null) {
builder.append("tokenValue=<TOKEN>");
}
this.display = builder.toString();
}
@Override
public void sessionCreated(HttpSessionEvent ev) {
HttpSession session = ev.getSession();
String id = session.getId();
sessions.add(session);
//System.out.println("SESSION: " + id + " was created");
}
public static String info(HttpSession s) {
if (s==null) return "null";
String hh = getContextPath(s);
if (Strings.isBlank(hh)) hh = getBundle(s);
if (Strings.isBlank(hh)) {
hh = s instanceof Session ? info( ((Session)s).getSessionHandler() ) : "<non-jetty>";
}
return ""+s+"["+s.getId()+" @ "+hh+"]";
}
/**
* Returns a session ID from underlying session.
*
* @return a session ID from underlying session, or null if session does not exist.
*/
public String id(){
HttpServletRequest r = RequestContext.getHttpRequest();
if(r == null){
return null;
}
HttpSession session = r.getSession(false);
return session == null ? null : session.getId();
}
/**
* Session Created
* @param sessionEvent
*/
@Override
public void sessionCreated(HttpSessionEvent sessionEvent) {
// Get the session that was created
HttpSession session = sessionEvent.getSession();
// Store something in the session, and log a message
try {
if( log.isDebugEnabled() ) {
log.debug(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> created sessionEvent=" + sessionEvent);
log.debug("Session created=" + session.getId());
}
String appName = sessionEvent.getSession().getServletContext().getContextPath();
SessionMonitorMBean sessionMonitorMBean = KhanSessionManager.getInstance(appName).getSessionMonitor();
if( sessionMonitorMBean != null )
sessionMonitorMBean.sessionCreated();
if( session != null && session.getId() != null) {
SessionId.setKhanSessionId(session.getId(), SessionIdThreadStore.get());
}
SessionIdThreadStore.remove();
if (KhanSessionFilter.getKhanSessionConfig().isAllowDuplicateLogin() == false) {
// session.setAttribute("khan.uid", SessionLoginManager.getInstance());
session.setAttribute("khan.uid", null);
}
//KhanSessionManager.getInstance(appName).putSessionId(session);
} catch (Exception e) {
log.error("Error in setting session attribute: "
+ e.getMessage(), e);
}
}
protected String changeSessionId(HttpSession session) {
return session.getId();
}
@Override
protected String changeSessionId(HttpSession session) {
Request request = this.request;
if (!deployment.turnOffChangeSessionIdOnLogin()) return request.changeSessionId();
else return session.getId();
}
private void appendId(final SoyMapData root, final HttpSession session) {
if (session.getId() != null) {
root.put(prefix + "id", session.getId());
}
}
@Override
public String getRequestedSessionId() {
HttpSession session = getSession();
return (session != null ? session.getId() : null);
}
@RequestMapping(value = "/list.action", method = {RequestMethod.GET, RequestMethod.POST})
public Pollable<ModelAndView> list(ComAdmin admin, UserActivityLogForm listForm, Model model, HttpSession session) {
String sessionId = session.getId();
DateTimeFormatter datePickerFormatter = admin.getDateFormatter();
SimpleDateFormat localTableFormat = admin.getDateTimeFormat();
FormUtils.syncNumberOfRows(webStorage, ComWebStorage.USERLOG_OVERVIEW, listForm);
List<AdminEntry> admins = adminService.getAdminEntriesForUserActivityLog(admin);
List<AdminEntry> adminsFilter = admin.permissionAllowed(Permission.MASTERLOG_SHOW) ? null : admins;
model.addAttribute("userActions", Arrays.asList(UserActivityLogActions.values()));
model.addAttribute("admins", admins);
model.addAttribute("localeTableFormat", localTableFormat);
AgnUtils.setAdminDateTimeFormatPatterns(admin, model);
model.addAttribute("defaultDate", LocalDate.now().format(datePickerFormatter));
LocalDate dateFrom = listForm.getDateFrom().get(LocalDate.now(), datePickerFormatter);
LocalDate dateTo = listForm.getDateTo().get(LocalDate.now(), datePickerFormatter);
Map<String, Object> argumentsMap = new HashMap<>();
argumentsMap.put("sort", listForm.getSort());
argumentsMap.put("order", listForm.getDir());
argumentsMap.put("page", listForm.getPage());
argumentsMap.put("numberOfRows", listForm.getNumberOfRows());
argumentsMap.put("username", listForm.getUsername());
argumentsMap.put("dateFrom.date", listForm.getDateFrom().getDate());
argumentsMap.put("dateTo.date", listForm.getDateTo().getDate());
argumentsMap.put("description", listForm.getDescription());
PollingUid pollingUid = PollingUid.builder(sessionId, USER_ACTIVITY_LOG_KEY)
.arguments(argumentsMap.values().toArray(ArrayUtils.EMPTY_OBJECT_ARRAY))
.build();
Callable<ModelAndView> worker = () -> {
PaginatedListImpl<LoggedUserAction> loggedUserActions =
userActivityLogService.getUserActivityLogByFilter(
admin,
listForm.getUsername(),
listForm.getUserAction(),
dateFrom,
dateTo,
listForm.getDescription(),
listForm.getPage(),
listForm.getNumberOfRows(),
listForm.getSort(),
listForm.getDir(),
adminsFilter);
model.addAttribute(USER_ACTIVITY_LOG_KEY, loggedUserActions);
return new ModelAndView("useractivitylog_list", model.asMap());
};
ModelAndView modelAndView = new ModelAndView("redirect:/administration/useractivitylog/list.action",
argumentsMap);
return new Pollable<>(pollingUid, Pollable.DEFAULT_TIMEOUT, modelAndView, worker);
}
/**
* SCIPIO: Returns the session ID itself, for log display, without space and prefix;
* if no session, returns "[none]"; if hidden, returns "[hidden]".
* <p>
* NOTE: If request is available, prefer using {@link #getSessionIdForLog(HttpServletRequest)} instead.
*/
public static String getSessionIdForLog(HttpSession session) {
return showSessionIdInLog ? (session != null ? session.getId() : "[none]") : "[hidden]";
}
/**
* Obtains the session ID from the request, or "[none]" if no session present.
* <p>
* SCIPIO: 2018-12-11: This no longer forces session creation and now returns "[none]" instead of "unknown",
* which was inaccurate. Note that this was primarily used for log display, and previously this was miscoded
* such that it could never actually return "unknown"; therefore, if any code was checking the string "unknown",
* it never did anything anyway.
*/
public static String getSessionId(HttpServletRequest request) {
HttpSession session = request.getSession(false); // SCIPIO: use false!
return (session == null ? "[none]" : session.getId());
}