isRequestedSessionIdValid()源码实例Demo

javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid()源码实例Demo

下面列出了javax.servlet.http.HttpServletRequest#isRequestedSessionIdValid() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

@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;
}
 
源代码2 项目: javamelody   文件: PluginMonitoringFilter.java
private void registerSessionIfNeeded(HttpServletRequest httpRequest) {
	// rq: cette session peut-être dors et déjà invalide et c'est pourquoi on vérifie
	// isRequestedSessionIdValid
	if (httpRequest.isRequestedSessionIdValid()) {
		final HttpSession session = httpRequest.getSession(false);
		emulatedSessionListener.registerSessionIfNeeded(session);
	}
}
 
源代码3 项目: cxf   文件: HttpServletRequestSnapshot.java
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();
}
 
源代码4 项目: fess   文件: UserInfoHelper.java
public String getUserCode() {
    final HttpServletRequest request = LaRequestUtil.getRequest();

    String userCode = (String) request.getAttribute(Constants.USER_CODE);
    if (StringUtil.isNotBlank(userCode)) {
        return userCode;
    }

    userCode = getUserCodeFromRequest(request);
    if (StringUtil.isNotBlank(userCode)) {
        return userCode;
    }

    if (!request.isRequestedSessionIdValid()) {
        return null;
    }

    userCode = getUserCodeFromCookie(request);
    if (StringUtil.isBlank(userCode)) {
        userCode = getUserCodeFromUserBean(request);
        if (StringUtil.isBlank(userCode)) {
            userCode = getId();
        }
    }

    if (StringUtil.isNotBlank(userCode)) {
        updateUserSessionId(userCode);
    }
    return userCode;
}
 
源代码5 项目: openemm   文件: LoadBalancerFilter.java
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
	String loadBalancerActivation = (String) request.getAttribute( LOAD_BALANCER_ACTIVATION_ATTRIBUTE);
	
	// First, check if the request attribute showing the activation state of the node is present
	if( loadBalancerActivation != null) {
		
		// Request attribute is present, so the node is behind a load balancer
		if( logger.isDebugEnabled()) {
			logger.debug( "Load balancer activation is " + loadBalancerActivation);
		}

		// Check, if activation state of current node is "disabled".
		if( "DIS".equals( loadBalancerActivation)) {
			
			// The node is disabled.
			try {
				HttpServletRequest req = (HttpServletRequest) request;

				// Check validity of session ID
				if( !req.isRequestedSessionIdValid()) {
					// Session ID is not valid for the current node, the requests sends a redirect to system URL specified in property "system.url"
					if( logger.isInfoEnabled()) {
						logger.info( "Requested session is invalid.");
					}
					
					HttpServletResponse resp = (HttpServletResponse) response;
					resp.sendRedirect( systemUrl);
				} else {
					
					// The session ID seems to be valid for the current node, so processing will continue.
					if( logger.isInfoEnabled()) {
						logger.info( "Requested session is valid. Proceeding with request.");
					}
					
					filterChain.doFilter( request, response);
				}
					
			} catch( ClassCastException e) {
				// We had some problem with the request. It may be no HTTP request. Processing will continue without further checks.
				logger.warn( "No HttpServletRequest?", e);
				
				filterChain.doFilter( request, response);
			}
		} else {
			// The node is either active or stopped.
			if( logger.isInfoEnabled()) {
				logger.info( "Node not disabled.");
			}

			filterChain.doFilter( request, response);
		}
	} else {
		/*
		 *  We got no information about the activation state of the current node, so we have to assume,
		 *  that the node is not behind a load balancer and is active all the time.
		 */
		
		if( logger.isInfoEnabled()) {
			logger.info( "No information about load balancer activation found.");
		}
		
		filterChain.doFilter( request, response);
	}
}
 
源代码6 项目: Knowage-Server   文件: EngineCheckSessionFilter.java
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  	throws IOException, ServletException {
  	
  	logger.debug("IN");
  	
  	try {
  		
	if (request instanceof HttpServletRequest) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(false);
		boolean isValidSession = session != null;
		boolean isRequiredNewSession = false; // for those requests that require a new session anyway, 
											  // do not forward to session expired url
		String newSessionRequestAttr = httpRequest.getParameter(NEW_SESSION);
       	isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE");
       	boolean isRequestedSessionIdValid = httpRequest.isRequestedSessionIdValid();
		if (!isValidSession && !isRequestedSessionIdValid && !isRequiredNewSession) {
			// session has expired
			logger.debug("Session has expired!!");
			String sessionExpiredUrl = EnginConf.getInstance().getSessionExpiredUrl();
			if (sessionExpiredUrl == null) {
				logger.warn("Session expired URL not set!!! check engine-config.xml configuration");
			} else {
				logger.debug("Forwarding to " + sessionExpiredUrl);
				httpRequest.getRequestDispatcher(sessionExpiredUrl).forward(request, response);
				return;
			}
		}
	}
	
	chain.doFilter(request, response);
	
   } catch(Throwable t) {
   	logger.error("--------------------------------------------------------------------------------");
    logger.error("EngineCheckSessionFilter" + ":doFilter ServletException!!",t); 
	logger.error(" msg: [" + t.getMessage() + "]"); 
	Throwable z = t.getCause(); 
	if(z != null) {
		logger.error("-----------------------------");
		logger.error("ROOT CAUSE:");
		logger.error("-----------------------------"); 
		logger.error(" msg: ["+ z.getMessage() + "]"); 
		logger.error(" stacktrace:");
	}
	t.printStackTrace(); 
   	throw new ServletException(t);
} finally {
	logger.debug("OUT");
}
	
  }
 
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
  	throws IOException, ServletException {
  	
  	//logger.debug("IN");
  	
  	try {
  		
	if (request instanceof HttpServletRequest) {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpSession session = httpRequest.getSession(false);
		boolean isValidSession = session != null;
		boolean isRequiredNewSession = false; // for those requests that require a new session anyway, 
											  // do not forward to session expired url
		String newSessionRequestAttr = httpRequest.getParameter(NEW_SESSION);
       	isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE");
       	boolean isRequestedSessionIdValid = httpRequest.isRequestedSessionIdValid();
		if (!isValidSession && !isRequestedSessionIdValid && !isRequiredNewSession) {
			// session has expired
			//logger.debug("Session has expired!!");
			String sessionExpiredUrl = getSessionExpiredUrl();
			if (sessionExpiredUrl == null || sessionExpiredUrl.trim().equals("")) {
				logger.warn("Session expired URL not set!!! check engine-config.xml configuration");
			} else {
				//logger.debug("Forwarding to " + sessionExpiredUrl);
				httpRequest.getRequestDispatcher(sessionExpiredUrl).forward(request, response);
				return;
			}
		}
	}
	
	chain.doFilter(request, response);
	
   } catch(Throwable t) {
   	logger.error("--------------------------------------------------------------------------------");
    logger.error("EngineCheckSessionFilter" + ":doFilter ServletException!!",t); 
	logger.error(" msg: [" + t.getMessage() + "]"); 
	Throwable z = t.getCause(); 
	if(z != null) {
		logger.error("-----------------------------");
		logger.error("ROOT CAUSE:");
		logger.error("-----------------------------"); 
		logger.error(" msg: ["+ z.getMessage() + "]"); 
		logger.error(" stacktrace:");
	}
	t.printStackTrace(); 
   	throw new ServletException(t);
} finally {
	//logger.debug("OUT");
}
	
  }
 
源代码8 项目: mycore   文件: MCRServlet.java
public static MCRSession getSession(HttpServletRequest req) {
    boolean reusedSession = req.isRequestedSessionIdValid();
    HttpSession theSession = req.getSession(true);
    if (reusedSession) {
        LOGGER.debug(() -> "Reused HTTP session: " + theSession.getId() + ", created: " + LocalDateTime
            .ofInstant(Instant.ofEpochMilli(theSession.getCreationTime()), ZoneId.systemDefault()));
    } else {
        LOGGER.info(() -> "Created new HTTP session: " + theSession.getId());
    }
    MCRSession session = null;

    MCRSession fromHttpSession = Optional
        .ofNullable((MCRSessionResolver) theSession.getAttribute(ATTR_MYCORE_SESSION))
        .flatMap(MCRSessionResolver::resolveSession)
        .orElse(null);

    MCRSessionMgr.unlock();
    if (fromHttpSession != null && fromHttpSession.getID() != null) {
        // Take session from HttpSession with servlets
        session = fromHttpSession;

        String lastIP = session.getCurrentIP();
        String newIP = MCRFrontendUtil.getRemoteAddr(req);

        try {
            if (!MCRFrontendUtil.isIPAddrAllowed(lastIP, newIP)) {
                LOGGER.warn("Session steal attempt from IP {}, previous IP was {}. Session: {}", newIP, lastIP,
                    session);
                MCRSessionMgr.releaseCurrentSession();
                session.close(); //MCR-1409 do not leak old session
                MCRSessionMgr.unlock();//due to release above
                session = MCRSessionMgr.getCurrentSession();
                session.setCurrentIP(newIP);
            }
        } catch (UnknownHostException e) {
            throw new MCRException("Wrong transformation of IP address for this session.", e);
        }
    } else {
        // Create a new session
        session = MCRSessionMgr.getCurrentSession();
    }

    // Store current session in HttpSession
    theSession.setAttribute(ATTR_MYCORE_SESSION, new MCRSessionResolver(session));
    // store the HttpSession ID in MCRSession
    if (session.put("http.session", theSession.getId()) == null) {
        //first request
        session.beginTransaction(); //for MCRTranslation.getAvailableLanguages()
        try {
            String acceptLanguage = req.getHeader("Accept-Language");
            if (acceptLanguage != null) {
                List<Locale.LanguageRange> languageRanges = Locale.LanguageRange.parse(acceptLanguage);
                LOGGER.debug("accept languages: {}", languageRanges);
                MCRSession finalSession = session;
                Optional
                    .ofNullable(Locale.lookupTag(languageRanges, MCRTranslation.getAvailableLanguages()))
                    .ifPresent(selectedLanguage -> {
                        LOGGER.debug("selected language: {}", selectedLanguage);
                        finalSession.setCurrentLanguage(selectedLanguage);
                    });
            }
        } finally {
            if (session.transactionRequiresRollback()) {
                session.rollbackTransaction();
            }
            session.commitTransaction();
        }
    }
    // Forward MCRSessionID to XSL Stylesheets
    req.setAttribute("XSL.MCRSessionID", session.getID());

    return session;
}
 
源代码9 项目: yawl   文件: LoginFilter.java
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
	return (httpServletRequest.getRequestedSessionId() != null) &&
               !httpServletRequest.isRequestedSessionIdValid();
}
 
源代码10 项目: yawl   文件: SessionTimeoutFilter.java
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
    return (httpServletRequest.getRequestedSessionId() != null) &&
           !httpServletRequest.isRequestedSessionIdValid();
}
 
源代码11 项目: yawl   文件: SessionTimeoutFilter.java
private boolean isInvalidSession(HttpServletRequest httpServletRequest) {
    return (httpServletRequest.getRequestedSessionId() != null) &&
           !httpServletRequest.isRequestedSessionIdValid();
}
 
protected void processTCKReq(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

  PortletRequest portletReq = (PortletRequest) request.getAttribute("javax.portlet.request");
  PortletResponse portletResp = (PortletResponse) request.getAttribute("javax.portlet.response");
  PortletSession portletSession = portletReq.getPortletSession();
  

  PrintWriter writer = ((MimeResponse) portletResp).getWriter();

  JSR286SpecTestCaseDetails tcd = new JSR286SpecTestCaseDetails();

  /* TestCase: V2AddlEnvironmentTests_SPEC2_18_Sessions_httpSession5 */
  /* Details: "If the PortletSession object is invalidated by a */
  /* portlet, the portlet container must invalidate the associated */
  /* HttpSession object" */
  {
     String tcid = portletReq.getParameter(BUTTON_PARAM_NAME);
     if (tcid == null || !tcid.equals(V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5)) {
        
        // generate test link 
        
        PortletURL rurl = ((MimeResponse)portletResp).createRenderURL();
        rurl.setParameter(BUTTON_PARAM_NAME, V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5);
        TestLink tl = new TestLink(V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5, rurl);
        tl.writeTo(writer);
     } else {
        
        // perform test
        
        TestResult result = tcd.getTestResultFailed(V2ADDLENVIRONMENTTESTS_SPEC2_18_SESSIONS_HTTPSESSION5);
        portletSession.invalidate();
        if (!request.isRequestedSessionIdValid()) {
          result.setTcSuccess(true);
        } else {
          result.appendTcDetail("Failed because session is not invalidated.");
        }
        result.writeTo(writer);
     }
  }
  
}