Java Code Examples for javax.servlet.http.HttpServletRequest#getRequestedSessionId()

The following examples show how to use javax.servlet.http.HttpServletRequest#getRequestedSessionId() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LogUtils.java    From es with Apache License 2.0 6 votes vote down vote up
/**
 * 记录访问日志
 * [username][jsessionid][ip][accept][UserAgent][url][params][Referer]
 *
 * @param request
 */
public static void logAccess(HttpServletRequest request) {
    String username = getUsername();
    String jsessionId = request.getRequestedSessionId();
    String ip = IpUtils.getIpAddr(request);
    String accept = request.getHeader("accept");
    String userAgent = request.getHeader("User-Agent");
    String url = request.getRequestURI();
    String params = getParams(request);
    String headers = getHeaders(request);

    StringBuilder s = new StringBuilder();
    s.append(getBlock(username));
    s.append(getBlock(jsessionId));
    s.append(getBlock(ip));
    s.append(getBlock(accept));
    s.append(getBlock(userAgent));
    s.append(getBlock(url));
    s.append(getBlock(params));
    s.append(getBlock(headers));
    s.append(getBlock(request.getHeader("Referer")));
    getAccessLog().info(s.toString());
}
 
Example 2
Source File: MemberOnlineUtils.java    From Spring-Boot-Book with Apache License 2.0 6 votes vote down vote up
public static void memberOnline(HttpServletRequest request) throws Exception
{

    String jsessionId = request.getRequestedSessionId();
    String ip = IpUtils.getIpAddr(request);
    String accept = request.getHeader("accept");
    String userAgent = request.getHeader("User-Agent");
    String url = request.getRequestURI();


    StringBuilder s = new StringBuilder();
    s.append(jsessionId);
    s.append(ip);
    s.append(accept);
    s.append(userAgent);
    s.append(url);
    s.append(request.getHeader("Referer"));

}
 
Example 3
Source File: LogUtils.java    From supplierShop with MIT License 6 votes vote down vote up
/**
 * 记录访问日志 [username][jsessionid][ip][accept][UserAgent][url][params][Referer]
 *
 * @param request
 * @throws Exception
 */
public static void logAccess(HttpServletRequest request) throws Exception
{
    String username = getUsername();
    String jsessionId = request.getRequestedSessionId();
    String ip = IpUtils.getIpAddr(request);
    String accept = request.getHeader("accept");
    String userAgent = request.getHeader("User-Agent");
    String url = request.getRequestURI();
    String params = getParams(request);

    StringBuilder s = new StringBuilder();
    s.append(getBlock(username));
    s.append(getBlock(jsessionId));
    s.append(getBlock(ip));
    s.append(getBlock(accept));
    s.append(getBlock(userAgent));
    s.append(getBlock(url));
    s.append(getBlock(params));
    s.append(getBlock(request.getHeader("Referer")));
    getAccessLog().info(s.toString());
}
 
Example 4
Source File: OriginCheckFilter.java    From teammates with GNU General Public License v2.0 6 votes vote down vote up
private String getCsrfTokenErrorIfAny(HttpServletRequest request) {
    String csrfToken = request.getHeader(Const.CsrfConfig.TOKEN_HEADER_NAME);
    if (csrfToken == null || csrfToken.isEmpty()) {
        return "Missing CSRF token.";
    }

    String sessionId = request.getRequestedSessionId();
    if (sessionId == null) {
        // Newly-created session
        sessionId = request.getSession().getId();
    }

    try {
        return sessionId.startsWith(StringHelper.decrypt(csrfToken)) ? null : "Invalid CSRF token.";
    } catch (InvalidParametersException e) {
        return "Invalid CSRF token.";
    }
}
 
Example 5
Source File: LogUtils.java    From NutzSite with Apache License 2.0 6 votes vote down vote up
/**
 * 记录访问日志 [username][jsessionid][ip][accept][UserAgent][url][params][Referer]
 *
 * @param request
 */
public static void logAccess(HttpServletRequest request)
{
    String username = getUsername();
    String jsessionId = request.getRequestedSessionId();
    String ip = IpUtils.getIpAddr(request);
    String accept = request.getHeader("accept");
    String userAgent = request.getHeader("User-Agent");
    String url = request.getRequestURI();
    String params = getParams(request);

    StringBuilder s = new StringBuilder();
    s.append(getBlock(username));
    s.append(getBlock(jsessionId));
    s.append(getBlock(ip));
    s.append(getBlock(accept));
    s.append(getBlock(userAgent));
    s.append(getBlock(url));
    s.append(getBlock(params));
    s.append(getBlock(request.getHeader("Referer")));
    getAccessLog().info(s.toString());
}
 
Example 6
Source File: MyInvalidSessionStrategy.java    From base-admin with MIT License 6 votes vote down vote up
@Override
public void onInvalidSessionDetected(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws IOException, ServletException {
    HttpSession session = httpServletRequest.getSession();
    String sessionId = httpServletRequest.getRequestedSessionId();
    if(!session.isNew()){
        //内部重定向
        httpServletResponse.sendRedirect("/loginPage");
    }else{
        //直接输出js脚本跳转
        httpServletResponse.setContentType("text/html;charset=UTF-8");
        httpServletResponse.getWriter().print("<script type='text/javascript'>window.location.href = \"/loginPage\"</script>");
    }
    SessionInformation sessionInformation = sessionRegistry.getSessionInformation(sessionId);
    if(sessionInformation != null){
        User user = (User) sessionInformation.getPrincipal();
        sessionRegistry.removeSessionInformation(sessionId);
        log.info("剔除过期用户:"+user.getUsername());
    }
    log.info("session失效处理 " + sessionRegistry.getAllPrincipals().size()+"");
    httpServletResponse.flushBuffer();
}
 
Example 7
Source File: SessionController.java    From FEBS-Security with Apache License 2.0 6 votes vote down vote up
@RequestMapping("session/kickout")
@ResponseBody
@PreAuthorize("hasAuthority('session:kickout')")
public ResponseBo kickOut(String sessionId, HttpServletRequest request, HttpServletResponse response) {
    try {
        String currentSessionId = request.getRequestedSessionId();
        sessionRegistry.getSessionInformation(sessionId).expireNow();
        if (StringUtils.equals(sessionId, currentSessionId)) {
            return ResponseBo.ok("refresh");
        } else {
            return ResponseBo.ok();
        }
    } catch (Exception e) {
        log.error("踢出用户失败", e);
        return ResponseBo.error("踢出用户失败,请联系网站管理员!");
    }
}
 
Example 8
Source File: RequestUtils.java    From Lottery with GNU General Public License v2.0 6 votes vote down vote up
/**
 * 获得请求的session id,但是HttpServletRequest#getRequestedSessionId()方法有一些问题。
 * 当存在部署路径的时候,会获取到根路径下的jsessionid。
 * 
 * @see HttpServletRequest#getRequestedSessionId()
 * 
 * @param request
 * @return
 */
public static String getRequestedSessionId(HttpServletRequest request) {
	String sid = request.getRequestedSessionId();
	String ctx = request.getContextPath();
	// 如果session id是从url中获取,或者部署路径为空,那么是在正确的。
	if (request.isRequestedSessionIdFromURL() || StringUtils.isBlank(ctx)) {
		return sid;
	} else {
		// 手动从cookie获取
		Cookie cookie = CookieUtils.getCookie(request,
				Constants.JSESSION_COOKIE);
		if (cookie != null) {
			return cookie.getValue();
		} else {
			return request.getSession().getId();
		}
	}

}
 
Example 9
Source File: LogUtils.java    From LuckyFrameWeb with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * 记录访问日志 [username][jsessionid][ip][accept][UserAgent][url][params][Referer]
 */
public static void logAccess(HttpServletRequest request)
{
    String username = getUsername();
    String jsessionId = request.getRequestedSessionId();
    String ip = IpUtils.getIpAddr(request);
    String accept = request.getHeader("accept");
    String userAgent = request.getHeader("User-Agent");
    String url = request.getRequestURI();
    String params = getParams(request);

    String s = getBlock(username) +
            getBlock(jsessionId) +
            getBlock(ip) +
            getBlock(accept) +
            getBlock(userAgent) +
            getBlock(url) +
            getBlock(params) +
            getBlock(request.getHeader("Referer"));
    getAccessLog().info(s);
}
 
Example 10
Source File: SessionUtil.java    From teamcity-oauth with Apache License 2.0 5 votes vote down vote up
@NotNull
static String getSessionId(@NotNull final HttpServletRequest request) {
    // we must use requested session id, if it is presented, and only if not, then we can use current session id, see TW-23821
    final String requestedSessionId = request.getRequestedSessionId();
    if (requestedSessionId != null) {
        return requestedSessionId;
    }
    return request.getSession().getId();
}
 
Example 11
Source File: TestCoyoteAdapter.java    From tomcatsrc with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter pw = resp.getWriter();
    String sessionId = req.getRequestedSessionId();
    if (sessionId == null) {
        sessionId = "none";
    }
    pw.write(sessionId);
}
 
Example 12
Source File: DefaultAuthenticationEntryPoint.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
@Override
protected String determineUrlToUseForThisRequest(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException exception) {
    val url = super.determineUrlToUseForThisRequest(request, response, exception);

    if (request.getRequestedSessionId() != null && !request.isRequestedSessionIdValid()) {
        if (log.isDebugEnabled()) {
            log.debug("セッションがタイムアウトしました。");
        }

        return this.loginTimeoutUrl;
    }

    return url;
}
 
Example 13
Source File: TestCoyoteAdapter.java    From Tomcat7.0.67 with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter pw = resp.getWriter();
    String sessionId = req.getRequestedSessionId();
    if (sessionId == null) {
        sessionId = "none";
    }
    pw.write(sessionId);
}
 
Example 14
Source File: TestRequestDispatcher.java    From joynr with Apache License 2.0 5 votes vote down vote up
@Override
public void doHandle(String target,
                     Request baseRequest,
                     HttpServletRequest request,
                     HttpServletResponse response) throws IOException, ServletException {

    String sessionId = request.getRequestedSessionId();

    if (sessionId == null) {
        String contextPath = forwardRoundRobin(baseRequest, response);

        // check if a session has been created in this request
        String location = response.getHeader("Location");
        if (location != null && Utilities.isSessionEncodedInUrl(location, "jsessionid")) {
            String createdSessionId = Utilities.getSessionId(location, "jsessionid");

            ClusterNode sessionCreatingInstance = getSessionCreatingServerInstance(createdSessionId);

            if (sessionCreatingInstance != null) {
                sessionStore.put(createdSessionId, sessionCreatingInstance.getContextPath());
                logger.debug("Request created a session encoded url that was created at server instance {}. Stored session ID {} for that instance",
                             sessionCreatingInstance.getContextPath(),
                             createdSessionId);
            } else {
                sessionStore.put(createdSessionId, contextPath);
                logger.debug("Request created a session encoded url. Stored session ID {} for that context {}",
                             createdSessionId,
                             contextPath);
            }
        }

    } else {

        String targetPath = sessionStore.get(sessionId);

        if (targetPath == null) {
            targetPath = forwardRoundRobin(baseRequest, response);
            sessionStore.put(sessionId, targetPath);
            logger.debug("Created new target path {} for session {}", targetPath, sessionId);
        } else {
            logger.debug("Applying sticky session pattern for target path {} and session {}",
                         targetPath,
                         sessionId);
            forwardToUrl(targetPath, baseRequest, response);
        }

    }

}
 
Example 15
Source File: HttpServletRequestSnapshot.java    From cxf with Apache License 2.0 5 votes vote down vote up
public HttpServletRequestSnapshot(HttpServletRequest request) {
    super(request);
    authType = request.getAuthType();
    characterEncoding = request.getCharacterEncoding();
    contentLength = request.getContentLength();
    contentType = request.getContentType();
    contextPath = request.getContextPath();
    cookies = request.getCookies();
    requestHeaderNames = request.getHeaderNames();
    Enumeration<String> tmp = request.getHeaderNames();
    while (tmp.hasMoreElements()) {
        String key = tmp.nextElement();
        headersMap.put(key, request.getHeaders(key));
    }
    localAddr = request.getLocalAddr();
    local = request.getLocale();
    localName = request.getLocalName();
    localPort = request.getLocalPort();
    method = request.getMethod();
    pathInfo = request.getPathInfo();
    pathTranslated = request.getPathTranslated();
    protocol = request.getProtocol();
    queryString = request.getQueryString();
    remoteAddr = request.getRemoteAddr();
    remoteHost = request.getRemoteHost();
    remotePort = request.getRemotePort();
    remoteUser = request.getRemoteUser();
    requestURI = request.getRequestURI();
    requestURL = request.getRequestURL();
    requestedSessionId = request.getRequestedSessionId();
    schema = request.getScheme();
    serverName = request.getServerName();
    serverPort = request.getServerPort();
    servletPath = request.getServletPath();
    if (request.isRequestedSessionIdValid()) {
        session = request.getSession();
    }
    principal = request.getUserPrincipal();
}
 
Example 16
Source File: TestCoyoteAdapter.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    resp.setContentType("text/plain");
    PrintWriter pw = resp.getWriter();
    String sessionId = req.getRequestedSessionId();
    if (sessionId == null) {
        sessionId = "none";
    }
    pw.write(sessionId);
}
 
Example 17
Source File: FebsLogoutHandler.java    From FEBS-Security with Apache License 2.0 4 votes vote down vote up
@Override
public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
    String sessionId = request.getRequestedSessionId();
    if (sessionId != null)
        sessionRegistry.removeSessionInformation(sessionId);
}
 
Example 18
Source File: RequestServlet.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	logger.info("访问 doGet");

	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");

	response.setContentType("text/html");

	String authType = request.getAuthType();
	String localAddr = request.getLocalAddr();
	Locale locale = request.getLocale();
	String localName = request.getLocalName();
	String contextPath = request.getContextPath();
	int localPort = request.getLocalPort();
	String method = request.getMethod();
	String pathInfo = request.getPathInfo();
	String pathTranslated = request.getPathTranslated();
	String protocol = request.getProtocol();
	String queryString = request.getQueryString();
	String remoteAddr = request.getRemoteAddr();
	int port = request.getRemotePort();
	String remoteUser = request.getRemoteUser();
	String requestedSessionId = request.getRequestedSessionId();
	String requestURI = request.getRequestURI();
	StringBuffer requestURL = request.getRequestURL();
	String scheme = request.getScheme();
	String serverName = request.getServerName();
	int serverPort = request.getServerPort();
	String servletPath = request.getServletPath();
	Principal userPrincipal = request.getUserPrincipal();

	String accept = request.getHeader("accept");
	String referer = request.getHeader("referer");
	String userAgent = request.getHeader("user-agent");

	String serverInfo = this.getServletContext().getServerInfo();

	PrintWriter out = response.getWriter();
	out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
	out.println("<HTML>");

	// 这里<title></title>之间的信息在浏览器中显示为标题
	out.println("  <HEAD><TITLE>Request Servlet</TITLE></HEAD>");
	out.println("  <style>body, font, td, div {font-size:12px; line-height:18px; }</style>");
	out.println("  <BODY>");

	out.println("<b>您的IP为</b> " + remoteAddr + "<b>;您使用</b> " + getOS(userAgent) + " <b>操作系统</b>,"
		+ getNavigator(userAgent) + " <b>。您使用</b> " + getLocale(locale) + "。<br/>");
	out.println("<b>服务器IP为</b> " + localAddr + localAddr + "<b>;服务器使用</b> " + serverPort + " <b>端口,您的浏览器使用了</b> "
		+ port + " <b>端口访问本网页。</b><br/>");
	out.println("<b>服务器软件为</b>:" + serverInfo + "。<b>服务器名称为</b> " + localName + "。<br/>");
	out.println("<b>您的浏览器接受</b> " + getAccept(accept) + "。<br/>");
	out.println("<b>您从</b> " + referer + " <b>访问到该页面。</b><br/>");
	out.println("<b>使用的协议为</b> " + protocol + "。<b>URL协议头</b> " + scheme + ",<b>服务器名称</b> " + serverName
		+ ",<b>您访问的URI为</b> " + requestURI + "。<br/>");
	out.println("<b>该 Servlet 路径为</b> " + servletPath + ",<b>该 Servlet 类名为</b> " + this.getClass().getName()
		+ "。<br/>");
	out.println("<b>本应用程序在硬盘的根目录为</b> " + this.getServletContext().getRealPath("") + ",<b>网络相对路径为</b> "
		+ contextPath + "。 <br/>");

	out.println("<br/>");

	out.println("<br/><br/><a href=" + requestURI + "> 点击刷新本页面 </a>");

	out.println("  </BODY>");
	out.println("</HTML>");
	out.flush();
	out.close();
}
 
Example 19
Source File: LoginFilter.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
	return (httpServletRequest.getRequestedSessionId() != null) &&
               !httpServletRequest.isRequestedSessionIdValid();
}
 
Example 20
Source File: SessionTimeoutFilter.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
    return (httpServletRequest.getRequestedSessionId() != null) &&
           !httpServletRequest.isRequestedSessionIdValid();
}