Java Code Examples for javax.servlet.http.HttpSession#setMaxInactiveInterval()

The following examples show how to use javax.servlet.http.HttpSession#setMaxInactiveInterval() . 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: SessionListener.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
/** HttpSessionListener interface */
   @Override
   public void sessionCreated(HttpSessionEvent sessionEvent) {
if (sessionEvent == null) {
    return;
}
HttpSession session = sessionEvent.getSession();
session.setMaxInactiveInterval(Configuration.getAsInt(ConfigurationKeys.INACTIVE_TIME));

//set server default locale for STURTS and JSTL. This value should be overwrite
//LocaleFilter class. But this part code can cope with login.jsp Locale.
if (session != null) {
    String defaults[] = LanguageUtil.getDefaultLangCountry();
    Locale preferredLocale = new Locale(defaults[0] == null ? "" : defaults[0],
	    defaults[1] == null ? "" : defaults[1]);
    session.setAttribute(LocaleFilter.PREFERRED_LOCALE_KEY, preferredLocale);
    Config.set(session, Config.FMT_LOCALE, preferredLocale);
}
   }
 
Example 2
Source File: UserSession.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param hreq
 * @return associated user session
 */
public static UserSession getUserSession(HttpServletRequest hreq) {
    // get existing or create new session
    final HttpSession httpSession = hreq.getSession(true);
    if (httpSession.isNew()) {
        // set a possibly changed session timeout interval
        int currentSessionTimeout = httpSession.getMaxInactiveInterval();
        if (currentSessionTimeout != getGlobalSessionTimeout()) {
            httpSession.setMaxInactiveInterval(getGlobalSessionTimeout());
            if (log.isDebugEnabled()) {
                log.debug("HTTP session timeout changed [id=" + httpSession.getId() + ": " + currentSessionTimeout + "s => " + getGlobalSessionTimeout() + "s]");
            }
        }
    }

    return getUserSession(httpSession);
}
 
Example 3
Source File: TerminateWebSessionListener.java    From cas4.0.x-server-wechat with Apache License 2.0 6 votes vote down vote up
@Override
public void sessionEnded(final RequestContext context, final FlowSession session, final String outcome,
                         final AttributeMap output) {

    if ( session.isRoot() ) {
        final HttpServletRequest request = WebUtils.getHttpServletRequest(context);
        // get session but don't create it if it doesn't already exist
        final HttpSession webSession = request.getSession(false);

        if (webSession != null) {
            LOGGER.debug("Terminate web session {} in {} seconds", webSession.getId(), this.timeToDieInSeconds);
            // set the web session to die in timeToDieInSeconds
            webSession.setMaxInactiveInterval(this.timeToDieInSeconds);
        }
    }
}
 
Example 4
Source File: FormViewer.java    From yawl with GNU Lesser General Public License v3.0 6 votes vote down vote up
private void adjustSessionTimeout(WorkItemRecord wir) {

        // get new timeout value (if any)
        String rawValue = null;
        Element data = wir.getDataList();
        if (data != null) {
            rawValue = data.getChildText("ySessionTimeout");
        }

        // convert to int, remember current timeout, set new timeout (as secs)
        if (rawValue != null) {
            try {
                int minutes = new Integer(rawValue);
                HttpSession session = _sb.getExternalSession();
                _sb.setDefaultSessionTimeoutValue(session.getMaxInactiveInterval()) ;
                session.setMaxInactiveInterval(minutes * 60);
                _sb.setSessionTimeoutValueChanged(true);
            }
            catch (NumberFormatException nfe) {
                // bad timeout value supplied - nothing further to do
            }
        }
    }
 
Example 5
Source File: UserSession.java    From olat with Apache License 2.0 6 votes vote down vote up
/**
 * @param session
 * @return associated user session
 */
public static UserSession getUserSession(HttpSession session) {
    UserSession us;
    synchronized (session) {// o_clusterOK by:fj
        us = (UserSession) session.getAttribute(USERSESSIONKEY);
        if (us == null) {
            us = new UserSession();
            session.setAttribute(USERSESSIONKEY, us); // triggers the
            // valueBoundEvent -> nothing
            // more to do here
        }
    }
    // set a possible changed session timeout interval
    session.setMaxInactiveInterval(UserSession.sessionTimeoutInSec);
    return us;
}
 
Example 6
Source File: LoginServlet.java    From journaldev with MIT License 6 votes vote down vote up
protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {

	// get request parameters for userID and password
	String user = request.getParameter("user");
	String pwd = request.getParameter("pwd");
	
	if(userID.equals(user) && password.equals(pwd)){
		HttpSession session = request.getSession();
		session.setAttribute("user", "Pankaj");
		//setting session to expiry in 30 mins
		session.setMaxInactiveInterval(30*60);
		Cookie userName = new Cookie("user", user);
		userName.setMaxAge(30*60);
		response.addCookie(userName);
		response.sendRedirect("LoginSuccess.jsp");
	}else{
		RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
		PrintWriter out= response.getWriter();
		out.println("<font color=red>Either user name or password is wrong.</font>");
		rd.include(request, response);
	}

}
 
Example 7
Source File: AuthorizationFilter.java    From development with Apache License 2.0 5 votes vote down vote up
private void rollbackDefaultTimeout(HttpServletRequest httpRequest) {
    HttpSession session = httpRequest.getSession();
    Integer attributeInt = (Integer) session.getAttribute(Constants.SESS_ATTR_DEFAULT_TIMEOUT);
    if (attributeInt != null) {
        session.setMaxInactiveInterval(attributeInt.intValue());
        session.removeAttribute(Constants.SESS_ATTR_DEFAULT_TIMEOUT);
    }
}
 
Example 8
Source File: AuthenticationControllerTestIT.java    From blackduck-alert with Apache License 2.0 5 votes vote down vote up
@Test
public void userLogoutWithValidSessionTest() {
    ResponseFactory responseFactory = new ResponseFactory();
    AuthenticationController loginHandler = new AuthenticationController(null, null, responseFactory, csrfTokenRepository);
    HttpServletRequest request = new MockHttpServletRequest();
    HttpSession session = request.getSession(true);
    session.setMaxInactiveInterval(30);

    ResponseEntity<String> response = loginHandler.logout(request);
    assertEquals(HttpStatus.NO_CONTENT, response.getStatusCode());
}
 
Example 9
Source File: Ki4soClientLogoutFilter.java    From web-sso with Apache License 2.0 5 votes vote down vote up
@Override
public void doFilter(ServletRequest request, ServletResponse response,
		FilterChain chain) throws IOException, ServletException {
	HttpServletResponse servletResponse = (HttpServletResponse)response;
	HttpServletRequest servletRequest = (HttpServletRequest)request;
	
	//获得userId参数值。
	String userId = request.getParameter(WebConstants.USER_ID_PARAM_NAME);
	if(StringUtils.isEmpty(userId)){
		logger.warn(SESSIONID_IS_NULL);
		sendError(servletResponse,SESSIONID_IS_NULL);
		return;
	}
	if(!SessionStorage.containsKey(userId)){
		logger.warn(SESSIONID_IS_NOT_CONTATINS);
		sendError(servletResponse,SESSIONID_IS_NOT_CONTATINS);
		return;
	}
	HttpSession session = SessionStorage.get(userId);
	try{
		//本地应用已经登录,则进行登出处理。
		if(session!=null && session.getAttribute(Ki4soClientFilter.USER_STATE_IN_SESSION_KEY)!=null){
			if(session.getAttribute(Ki4soClientFilter.USER_STATE_IN_SESSION_KEY)!=null){
				//清除session中的值。
				session.setAttribute(Ki4soClientFilter.USER_STATE_IN_SESSION_KEY, null);
			}
			
			//若本定应用处理器不为空。
			if(appClientLogoutHandler!=null){
				//登出本应用。
				appClientLogoutHandler.logoutClient(servletRequest, servletResponse, userId);
			}
			
			//将session设置过期
			session.setMaxInactiveInterval(0);
			//移除session信息
			SessionStorage.remove(userId);
		}
		//响应登录结果。
		sendResponse(servletResponse);
	}
	catch (Exception e) {
		//响应登录结果。
		sendError(servletResponse);
	}
}
 
Example 10
Source File: LoginController.java    From spring-data-rest-acl with Apache License 2.0 5 votes vote down vote up
/**
 * api to set session timeout for current HttpSession. timeoutInSeconds is
 * optional parameter. If not set, will be defaulted to 24 hours (86400s)
 * 
 * @param timeoutInSeconds
 * @param httpSession
 * @return
 */
@RequestMapping(method = RequestMethod.PUT, value = "/loginsession/timeout")
public @ResponseBody
String setSessionTimeout(
		@RequestParam(value = "timeoutInSeconds", defaultValue = "86400") int timeoutInSeconds,
		HttpSession httpSession) {
	httpSession.setMaxInactiveInterval(timeoutInSeconds);
	return "httpSession timeout set to:"
			+ httpSession.getMaxInactiveInterval();
}
 
Example 11
Source File: SessionStorageJ2EEImpl.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
public boolean onRequestStart(cfSession Session, long sessionTimeOut, sessionUtility sessionInfo) {
	boolean sessionStart = false;
	
	// This will look for the HttpSession object and then get the necessary cfJ2EESessionData into action
	HttpSession	httpSess = Session.REQ.getSession( true );
	if ( httpSess == null )
		return false;
	
	cfSessionData sessionData = (cfSessionData)httpSess.getAttribute( appName );
	if ( sessionData == null || sessionTimeOut == 0 ){
		// Create a new instance, if none was found, or the timeout was 0 (which means delete it)
		sessionData	= new cfSessionData( appName );
		sessionStart = true;
		httpSess.setAttribute( appName, sessionData );
	} 

	// If sessionTimeout is -1 then we want to default to the session timeout value configured
	// in the J2EE web app's web.xml file.
	// If sessionTimeout is 0 then we don't want to set the session timeout.
	if ( sessionTimeOut > 0 ) {
		httpSess.setMaxInactiveInterval( (int)(sessionTimeOut/1000) );
	}
		
	sessionData.setSessionID( httpSess.getId() );
	Session.setQualifiedData( variableStore.SESSION_SCOPE, sessionData );

	return sessionStart;
}
 
Example 12
Source File: UserServiceImpl.java    From yunsleLive_room with MIT License 5 votes vote down vote up
@Override
    public StatusMessage userLogin(HttpSession session, String name, String password, String authcode) {
        try {
            User r = userDao.findByName(name);
//            //利用Redis,判断该用户是否已经登录
            if(isLogin(r.getName())) {
                return new StatusMessage(404, "error", "抱歉,该用户已经在其他地方登录!");
            }
            //校验验证码
            if(authcode != null && authcode == session.getAttribute("authcode")) {
                return new StatusMessage(404, "error", "验证码错误!");
            }
            // 用户名密码校验
            if(r != null && password.equals(r.getPassword())) {
                //登录成功,写入session,设置过期事件30分钟
                session.setMaxInactiveInterval(30 * 60);
                session.setAttribute("name", r.getName());
                //写入Redis
                redisTemplate.opsForList().rightPush("user", r.getName());
                return new StatusMessage(200, "success", "登录成功!");
            }else {
            //登录失败
                return new StatusMessage(404, "error", "登录失败,用户名或密码错误!");
            }
        }catch (Exception e){
            //后续日志输出
            System.err.println("数据库错误:"+e);
            //返回数据库错误信息
            return new StatusMessage(404, "error", "数据库错误:"+e);
        }
    }
 
Example 13
Source File: UserSessionUtils.java    From FlyCms with MIT License 5 votes vote down vote up
/**
 * 写入用户SESSION信息
 * 
 * @param request
 * @param user
 */
public void setLoginMember(HttpServletRequest request, HttpServletResponse response,boolean  keepLogin, User user){
    // 如果用户勾选保持登录,暂定过期时间为 3 年,否则为 120 分钟,单位为秒
    long liveSeconds =  keepLogin ? 3 * 365 * 24 * 60 * 60 : 120 * 60;
    // 传递给控制层的 cookie
    int maxAgeInSeconds = (int)(keepLogin ? liveSeconds : -1);
    // expireTime 用于设置 session 的过期时间点,需要转换成毫秒
    long expireTime = System.currentTimeMillis() + (liveSeconds * 1000);
    String sessionKey=Md5Utils.getMD5(String.valueOf(expireTime));
    HttpSession session=request.getSession(true);
    session.setMaxInactiveInterval(maxAgeInSeconds);
    user.setSessionKey(sessionKey);
    session.setAttribute(Const.SESSION_USER,user);

    Cookie cookie = new Cookie(siteConst.getSessionKey(),sessionKey);
    cookie.setPath("/");
    String domain =request.getServerName();
    if(!"127.0.0.1".equals(domain) && !"localhost".equals(domain)){
        cookie.setDomain(siteConst.getCookieDomain());
    }else{
        cookie.setDomain(domain);
    }
    cookie.setMaxAge(maxAgeInSeconds);
    response.addCookie(cookie);

    UserSession userSession=new UserSession();
    userSession.setSessionKey(sessionKey);
    userSession.setUserId(user.getUserId());
    userSession.setExpireTime(expireTime);
    userSession.setUpdateTime(new Date());
    if(userService.checkUserSessionByUserId(user.getUserId())){
        userService.updateUserSession(userSession);
    }else{
        userService.addUserSession(userSession);
    }
}
 
Example 14
Source File: RequestContext.java    From EserKnife with Apache License 2.0 5 votes vote down vote up
public static HttpSession getSession(){
    HttpServletRequest request=  getRequest();
    if(request == null){
        return null;
    }else {
        HttpSession session = getRequest().getSession(false);
        if(session == null){
            session = getRequest().getSession(true);
            session.setMaxInactiveInterval(1800);
        }
        return session;
    }

}
 
Example 15
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 5 votes vote down vote up
@POST
@Path("/" + Constants.RP_REGISTER_PATH)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response register(JsonObject input) {
    try{
        HttpSession session = request.getSession(false);
        if(session == null){
            return generateResponse(Response.Status.FORBIDDEN, WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1003"));
        }

        String username = (String) session.getAttribute(Constants.SESSION_USERNAME);
        if (!doesAccountExists(username)) {
            String regresponse = SKFSClient.register(username, getOrigin(), input);
            //On success, add user to database
            userdatabase.addUser(username);

            session.setAttribute(Constants.SESSION_USERNAME, username);
            session.setAttribute(Constants.SESSION_ISAUTHENTICATED, true);
            session.setMaxInactiveInterval(Constants.SESSION_TIMEOUT_VALUE);
            return generateResponse(Response.Status.OK, getResponseFromSKFSResponse(regresponse));
        } else {
            //If the user already exists, throw an error
            WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "register", "WEBAUTHN-WS-ERR-1001", username);
            return generateResponse(Response.Status.CONFLICT, WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1001"));
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
        WebauthnTutorialLogger.logp(Level.SEVERE, CLASSNAME, "register", "WEBAUTHN-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                WebauthnTutorialLogger.getMessageProperty("WEBAUTHN-WS-ERR-1000"));
    }
}
 
Example 16
Source File: WebUtil.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
public static void setSessionTimeout(HttpSession session) {
	int maxInactiveInterval;
	if (isTrustedHost()) {
		maxInactiveInterval = Settings.getInt(SettingCodes.SESSION_TIMEOUT_TRUSTED, Bundle.SETTINGS, DefaultSettings.SESSION_TIMEOUT_TRUSTED);
	} else {
		maxInactiveInterval = Settings.getInt(SettingCodes.SESSION_TIMEOUT, Bundle.SETTINGS, DefaultSettings.SESSION_TIMEOUT);
	}
	maxInactiveInterval *= 60;
	if (session != null) {
		session.setMaxInactiveInterval(maxInactiveInterval);
	} else {
		FacesContext context = FacesContext.getCurrentInstance();
		context.getExternalContext().setSessionMaxInactiveInterval(maxInactiveInterval);
	}
}
 
Example 17
Source File: TestCrawlerSessionManagerValve.java    From Tomcat8-Source-Read with MIT License 5 votes vote down vote up
private HttpSession createSessionExpectations(CrawlerSessionManagerValve valve, boolean isBot) {
    HttpSession session = EasyMock.createMock(HttpSession.class);
    if (isBot) {
        EasyMock.expect(session.getId()).andReturn("id").times(2);
        session.setAttribute(EasyMock.eq(valve.getClass().getName()), EasyMock.anyObject(HttpSessionBindingListener.class));
        EasyMock.expectLastCall();
        session.setMaxInactiveInterval(60);
        EasyMock.expectLastCall();
    }
    return session;
}
 
Example 18
Source File: AccountServiceImpl.java    From EasyML with Apache License 2.0 4 votes vote down vote up
/**
 * Set session time in HttpServletRequest
 */
public void setSessionExpireTime() {
	HttpServletRequest request = this.getThreadLocalRequest();
	HttpSession session = request.getSession();
	session.setMaxInactiveInterval(60 * 60 * 12);  			// expired after 12 days
}
 
Example 19
Source File: WebauthnService.java    From fido2 with GNU Lesser General Public License v2.1 4 votes vote down vote up
@POST
@Path("/" + Constants.RP_REGISTER_PATH)
@Consumes({MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_JSON})
public Response register(JsonObject input) {
    try{
        HttpSession session = request.getSession(false);
        if(session == null){
            return generateResponse(Response.Status.FORBIDDEN, POCLogger.getMessageProperty("POC-WS-ERR-1003"));
        }

        //Get information stored in session
        String email = (String) session.getAttribute(Constants.SESSION_EMAIL);
        String username = (String) session.getAttribute(Constants.SESSION_USERNAME);
        String firstName = (String) session.getAttribute(Constants.SESSION_FIRSTNAME);
        String lastName = (String) session.getAttribute(Constants.SESSION_LASTNAME);

        //Verify email was not used to generate another account
        if (doesEmailExist(email)) {
            POCLogger.logp(Level.SEVERE, CLASSNAME, "register", "POC-WS-ERR-1005", email);
            return generateResponse(Response.Status.CONFLICT,
                    POCLogger.getMessageProperty("POC-WS-ERR-1005"));
        }

        if (!doesAccountExist(username)) {
            String regresponse = SKFSClient.register(username, getOrigin(), input);
            //On success, add user to database
            userdatabase.addUser(email, username, firstName, lastName);

            //Remove registration request from DB
            registrationDB.deleteRegistration(email);
            session.removeAttribute(Constants.SESSION_FIRSTNAME);
            session.removeAttribute(Constants.SESSION_LASTNAME);
            session.removeAttribute(Constants.SESSION_EMAIL);

            session.setAttribute(Constants.SESSION_USERNAME, username);
            session.setAttribute(Constants.SESSION_ISAUTHENTICATED, true);
            session.setMaxInactiveInterval(Constants.SESSION_TIMEOUT_VALUE);
            System.out.println("Received from FIDO Server: " + regresponse);
            return generateResponse(Response.Status.OK, getResponseFromSKFSResponse(regresponse));
        } else {
            //If the user already exists, throw an error
            POCLogger.logp(Level.SEVERE, CLASSNAME, "register", "POC-WS-ERR-1001", username);
            return generateResponse(Response.Status.CONFLICT, POCLogger.getMessageProperty("POC-WS-ERR-1001"));
        }
    }
    catch (Exception ex) {
        ex.printStackTrace();
        POCLogger.logp(Level.SEVERE, CLASSNAME, "register", "POC-WS-ERR-1000", ex.getLocalizedMessage());
        return generateResponse(Response.Status.INTERNAL_SERVER_ERROR,
                POCLogger.getMessageProperty("POC-WS-ERR-1000"));
    }
}
 
Example 20
Source File: SessionBean.java    From yawl with GNU Lesser General Public License v3.0 4 votes vote down vote up
public void resetSessionTimeout() {
    HttpSession session = getExternalSession();
     if (defaultSessionTimeoutValue != session.getMaxInactiveInterval()) {
         session.setMaxInactiveInterval(defaultSessionTimeoutValue);
     }
}