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

The following examples show how to use javax.servlet.http.HttpSession#isNew() . 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: 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 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: PrimuServlet.java    From training with MIT License 6 votes vote down vote up
@Override
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
	HttpServletRequest httpRequest = (HttpServletRequest) request;
	HttpServletResponse httpResponse = (HttpServletResponse) response;
	
	
	
	
	HttpSession session = httpRequest.getSession();
	if (session.isNew()) {
		session.setAttribute("zar", new Random().nextInt(6) + 1);
	}
	
	
	httpResponse.setHeader("Content-Type", "text/plain");
	httpResponse.getWriter().println(
			"<html><body><h1>Hello Web !! " + 
					session.getAttribute("zar")+"</h1></body></html>");
	System.out.println("p1 = " + httpRequest.getParameter("p1"));
	System.out.println("p2 = " + httpRequest.getParameter("p2"));
}
 
Example 4
Source File: SessionDestroyedListener.java    From boubei-tss with Apache License 2.0 6 votes vote down vote up
public void sessionCreated(HttpSessionEvent event) {
    HttpSession session = event.getSession();
    
    // 设置 session 的过期时间
    if(session.isNew()){
        String configValue = ParamConfig.getAttribute(PX.SESSION_CYCLELIFE_CONFIG);
        try {
        	int cycleLife = Integer.parseInt(configValue);
session.setMaxInactiveInterval(cycleLife); // 以秒为单位
        } 
        catch(Exception e) { }
    }
    
    String sessionId = session.getId();
    String appCode = Context.getApplicationContext().getCurrentAppCode();
    log.debug("应用【" + appCode + "】里 sessionId为:" + sessionId
            + " 的session创建完成,有效期为:" + session.getMaxInactiveInterval() + " 秒 ");
    
    Context.sessionMap.put(sessionId, session);
}
 
Example 5
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
private void checkSession(HttpSession session, RequestContextIFace requestContext) throws SessionExpiredException {

		// start modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
		boolean isRequestedSessionIdValid = true;
		boolean isRequiredNewSession = false; // Zerbetto on 25-02-2008
		RequestContainer requestContainer = requestContext.getRequestContainer();

		if (session.isNew()) {
			isRequestedSessionIdValid = (requestContainer.getAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID) == null);
			String newSessionRequestAttr = (String) requestContainer.getServiceRequest().getAttribute(NEW_SESSION); // Zerbetto on 25-02-2008
			isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE"); // Zerbetto on 25-02-2008
		} // if (session.isNew())
		synchronized (session) {
			RequestContainer parentRequestContainer = (RequestContainer) session.getAttribute(Constants.REQUEST_CONTAINER);
			if (!Navigator.isNavigatorEnabled()) {
				if (parentRequestContainer == null)
					requestContainer.setSessionContainer(new SessionContainer(true));
				else
					requestContainer.setSessionContainer(parentRequestContainer.getSessionContainer());
			} else {
				if (parentRequestContainer == null)
					requestContainer.setSessionContainer(new SessionContainer(true));
				else {
					requestContainer.setSessionContainer(new SessionContainer(false));
					requestContainer.setParent(parentRequestContainer);
				} // if (parentRequestContainer == null) else
			} // if (!Navigator.isNavigatorEnabled())
			session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
		} // synchronized (session)
		if (!isRequestedSessionIdValid) {
			if (!isRequiredNewSession) { // Zerbetto on 25-02-2008
				TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.WARNING, "AdapterHTTP::service: sessione scaduta !");
				throw new SessionExpiredException(EMFErrorSeverity.ERROR, "Expired Session");
			} // Zerbetto on 25-02-2008
		} // if (!isRequestedSessionIdValid)
			// end modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
	}
 
Example 6
Source File: HttpServletResponseImpl.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
/**
 * Return <code>true</code> if the specified URL should be encoded with
 * a session identifier.  This will be true if all of the following
 * conditions are met:
 * <ul>
 * <li>The request we are responding to asked for a valid session
 * <li>The requested session ID was not received via a cookie
 * <li>The specified URL points back to somewhere within the web
 * application that is responding to this request
 * </ul>
 *
 * @param location Absolute URL to be validated
 */
private boolean isEncodeable(final String location) {

    if (location == null)
        return (false);

    // Is this an intra-document reference?
    if (location.startsWith("#"))
        return (false);

    // Are we in a valid session that is not using cookies?
    final HttpServletRequestImpl hreq = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getOriginalRequest();

    // Is URL encoding permitted
    if (!originalServletContext.getEffectiveSessionTrackingModes().contains(SessionTrackingMode.URL)) {
        return false;
    }

    final HttpSession session = hreq.getSession(false);
    if (session == null) {
        return false;
    } else if(hreq.isRequestedSessionIdFromCookie()) {
        return false;
    } else if (!hreq.isRequestedSessionIdFromURL() && !session.isNew()) {
        return false;
    }

    return doIsEncodeable(hreq, session, location);
}
 
Example 7
Source File: HttpSessionByCookieServletT.java    From servlet-core-learning with Apache License 2.0 5 votes vote down vote up
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
		throws ServletException, IOException {
	
	// 获取session
	// 如果是第一次请求的话,会创建一个HttpSeesion,等同于 req.getSession(true);
	// 如果已存在session,则会获取session。
	HttpSession session = req.getSession();
	
	if (session.isNew()) {
		// 设置session属性值	
		session.setAttribute("name", "Jeff");
	}
	// 获取SessionId
	String sessionId = session.getId();
	
	PrintWriter out = resp.getWriter();
	// 如果HttpSeesion是新建的话
	if (session.isNew()) {
		out.println("Hello,HttpSession! <br>The first response - SeesionId=" 
				+ sessionId + " <br>");
	} else {
		out.println("Hello,HttpSession! <br>The second response - SeesionId=" 
				+ sessionId + " <br>");
		// 从Session获取属性值
		out.println("The second-response - name: " 
				+ session.getAttribute("name"));
	}
	
}
 
Example 8
Source File: GeodeSessionStateServlet.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  HttpSession session = request.getSession();
  if (session.isNew()) {
    request.setAttribute("isNew", "Session is new.");
  } else {
    request.setAttribute("isNew", "Session already existing");
    session.setMaxInactiveInterval(90);
  }

  if (request.getParameter("action") != null) {
    if (request.getParameter("action").equals("Set Attribute")
        && request.getParameter("key") != null && !request.getParameter("value").equals("null")) {
      session.setAttribute(request.getParameter("key"), request.getParameter("value"));
    }

    if (request.getParameter("action").equals("Get Attribute")
        && request.getParameter("key") != null) {
      request.setAttribute("getKey", session.getAttribute(request.getParameter("key")));
    }

    if (request.getParameter("action").equals("Delete Attribute")
        && request.getParameter("key") != null) {
      session.removeAttribute(request.getParameter("key"));
    }
  }

  request.getRequestDispatcher("/index.jsp").forward(request, response);
}
 
Example 9
Source File: SingleLoginListener.java    From opencron with Apache License 2.0 5 votes vote down vote up
/**
 * 移除用户Session
 */
public synchronized static void removeUserSession(Long userId) {
    Map<Long, String> userSessionMap = getSessionIds();
    if (userSessionMap.containsKey(userId)) {
        String sessionId = userSessionMap.get(userId);
        HttpSession httpSession = singleLoginSessionMap.get(sessionId);
        if (!httpSession.isNew()) {
            httpSession.removeAttribute(OpencronTools.LOGIN_USER);
            //httpSession.invalidate();
        }
        singleLoginSessionMap.remove(sessionId);
    }
}
 
Example 10
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Check session.
 * 
 * @param session        the session
 * @param requestContext the request context
 * 
 * @throws SessionExpiredException the session expired exception
 */
private void checkSession(HttpSession session, RequestContextIFace requestContext) throws SessionExpiredException {

	// start modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
	boolean isRequestedSessionIdValid = true;
	boolean isRequiredNewSession = false; // Zerbetto on 25-02-2008
	RequestContainer requestContainer = requestContext.getRequestContainer();

	if (session.isNew()) {
		isRequestedSessionIdValid = (requestContainer.getAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID) == null);
		String newSessionRequestAttr = (String) requestContainer.getServiceRequest().getAttribute(NEW_SESSION); // Zerbetto on 25-02-2008
		isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE"); // Zerbetto on 25-02-2008
	} // if (session.isNew())
	synchronized (session) {
		RequestContainer parentRequestContainer = (RequestContainer) session.getAttribute(Constants.REQUEST_CONTAINER);
		if (!Navigator.isNavigatorEnabled()) {
			if (parentRequestContainer == null)
				requestContainer.setSessionContainer(new SessionContainer(true));
			else
				requestContainer.setSessionContainer(parentRequestContainer.getSessionContainer());
		} else {
			if (parentRequestContainer == null)
				requestContainer.setSessionContainer(new SessionContainer(true));
			else {
				requestContainer.setSessionContainer(new SessionContainer(false));
				requestContainer.setParent(parentRequestContainer);
			} // if (parentRequestContainer == null) else
		} // if (!Navigator.isNavigatorEnabled())
		session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
	} // synchronized (session)
	if (!isRequestedSessionIdValid) {
		if (!isRequiredNewSession) { // Zerbetto on 25-02-2008
			TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.WARNING, "AdapterHTTP::service: sessione scaduta !");
			throw new SessionExpiredException(EMFErrorSeverity.ERROR, "Expired Session");
		} // Zerbetto on 25-02-2008
	} // if (!isRequestedSessionIdValid)
		// end modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
}
 
Example 11
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Check session.
 * 
 * @param session        the session
 * @param requestContext the request context
 * 
 * @throws SessionExpiredException the session expired exception
 */
private void checkSession(HttpSession session, RequestContextIFace requestContext) throws SessionExpiredException {

	// start modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
	boolean isRequestedSessionIdValid = true;
	boolean isRequiredNewSession = false; // Zerbetto on 25-02-2008
	RequestContainer requestContainer = requestContext.getRequestContainer();

	if (session.isNew()) {
		isRequestedSessionIdValid = (requestContainer.getAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID) == null);
		String newSessionRequestAttr = (String) requestContainer.getServiceRequest().getAttribute(NEW_SESSION); // Zerbetto on 25-02-2008
		isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE"); // Zerbetto on 25-02-2008
	} // if (session.isNew())
	synchronized (session) {
		RequestContainer parentRequestContainer = (RequestContainer) session.getAttribute(Constants.REQUEST_CONTAINER);
		if (!Navigator.isNavigatorEnabled()) {
			if (parentRequestContainer == null)
				requestContainer.setSessionContainer(new SessionContainer(true));
			else
				requestContainer.setSessionContainer(parentRequestContainer.getSessionContainer());
		} else {
			if (parentRequestContainer == null)
				requestContainer.setSessionContainer(new SessionContainer(true));
			else {
				requestContainer.setSessionContainer(new SessionContainer(false));
				requestContainer.setParent(parentRequestContainer);
			} // if (parentRequestContainer == null) else
		} // if (!Navigator.isNavigatorEnabled())
		session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
	} // synchronized (session)
	if (!isRequestedSessionIdValid) {
		if (!isRequiredNewSession) { // Zerbetto on 25-02-2008
			TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.WARNING, "AdapterHTTP::service: sessione scaduta !");
			throw new SessionExpiredException(EMFErrorSeverity.ERROR, "Expired Session");
		} // Zerbetto on 25-02-2008
	} // if (!isRequestedSessionIdValid)
		// end modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
}
 
Example 12
Source File: GeodeSessionStateServlet.java    From geode-examples with Apache License 2.0 5 votes vote down vote up
protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
  HttpSession session = request.getSession();
  if (session.isNew()) {
    request.setAttribute("isNew", "Session is new.");
  } else {
    request.setAttribute("isNew", "Session already existing");
    session.setMaxInactiveInterval(90);
  }

  if (request.getParameter("action") != null) {
    if (request.getParameter("action").equals("Set Attribute")
        && request.getParameter("key") != null && !request.getParameter("value").equals("null")) {
      session.setAttribute(request.getParameter("key"), request.getParameter("value"));
    }

    if (request.getParameter("action").equals("Get Attribute")
        && request.getParameter("key") != null) {
      request.setAttribute("getKey", session.getAttribute(request.getParameter("key")));
    }

    if (request.getParameter("action").equals("Delete Attribute")
        && request.getParameter("key") != null) {
      session.removeAttribute(request.getParameter("key"));
    }
  }

  request.getRequestDispatcher("/index.jsp").forward(request, response);
}
 
Example 13
Source File: InvocationContextImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 14
Source File: HttpServletResponseImpl.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Return <code>true</code> if the specified URL should be encoded with
 * a session identifier.  This will be true if all of the following
 * conditions are met:
 * <ul>
 * <li>The request we are responding to asked for a valid session
 * <li>The requested session ID was not received via a cookie
 * <li>The specified URL points back to somewhere within the web
 * application that is responding to this request
 * </ul>
 *
 * @param location Absolute URL to be validated
 */
private boolean isEncodeable(final String location) {

    if (location == null)
        return (false);

    // Is this an intra-document reference?
    if (location.startsWith("#"))
        return (false);

    // Are we in a valid session that is not using cookies?
    final HttpServletRequestImpl hreq = exchange.getAttachment(ServletRequestContext.ATTACHMENT_KEY).getOriginalRequest();

    // Is URL encoding permitted
    if (!originalServletContext.getEffectiveSessionTrackingModes().contains(SessionTrackingMode.URL)) {
        return false;
    }

    final HttpSession session = hreq.getSession(false);
    if (session == null) {
        return false;
    } else if(hreq.isRequestedSessionIdFromCookie()) {
        return false;
    } else if (!hreq.isRequestedSessionIdFromURL() && !session.isNew()) {
        return false;
    }

    return doIsEncodeable(hreq, session, location);
}
 
Example 15
Source File: AntiXsrfFilter.java    From seed with Mozilla Public License 2.0 4 votes vote down vote up
@Override
protected boolean onPreHandle(ServletRequest request, ServletResponse response,
        Object mappedValue) {
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;
    final HttpSession session = httpServletRequest.getSession(false);

    // Only apply XSRF protection when there is a session
    if (session != null) {
        // If session is new, generate a token and put it in a cookie
        if (session.isNew()) {
            setXsrfCookie(httpServletResponse);
        }
        // Else, apply XSRF protection logic
        else {
            final boolean noCheck;
            if (mappedValue != null && ((String[]) mappedValue).length != 0) {
                noCheck = NO_CHECK.equals(((String[]) mappedValue)[0]);
            } else {
                noCheck = false;
            }

            if (!noCheck && !isRequestIgnored(httpServletRequest)) {
                String cookieToken = getTokenFromCookie(httpServletRequest);

                // If no cookie is available, send an error
                if (cookieToken == null) {
                    WebSecurityPlugin.sendErrorToClient((HttpServletResponse) response,
                            LOGGER,
                            HttpServletResponse.SC_FORBIDDEN,
                            "Missing CSRF protection token cookie",
                            null);
                    return false;
                }

                // Try to obtain the request token from a header
                String requestToken = getTokenFromHeader(httpServletRequest);

                // Fallback to query parameter if we didn't a token in the headers
                if (requestToken == null) {
                    requestToken = getTokenFromParameter(httpServletRequest);
                }

                // If no request token available, send an error
                if (requestToken == null) {
                    WebSecurityPlugin.sendErrorToClient((HttpServletResponse) response,
                            LOGGER,
                            HttpServletResponse.SC_FORBIDDEN,
                            "Missing CSRF protection token in the request headers",
                            null);
                    return false;
                }

                // If tokens don't match, send an error
                if (!cookieToken.equals(requestToken)) {
                    WebSecurityPlugin.sendErrorToClient((HttpServletResponse) response,
                            LOGGER,
                            HttpServletResponse.SC_FORBIDDEN,
                            "Request token does not match session token",
                            null);
                    return false;
                }

                // Regenerate token if per-request tokens are in use
                if (xsrfConfig.isPerRequestToken()) {
                    setXsrfCookie(httpServletResponse);
                }
            }
        }
    }
    return true;
}
 
Example 16
Source File: AdapterHTTP.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
private void checkSession(HttpSession session, RequestContextIFace requestContext)
	throws SessionExpiredException {
	
	// start modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
    boolean isRequestedSessionIdValid = true;
    boolean isRequiredNewSession = false;    // Zerbetto on 25-02-2008
    RequestContainer requestContainer = requestContext.getRequestContainer();
            
    if (session.isNew()) {
        isRequestedSessionIdValid = (requestContainer.getAttribute(HTTP_REQUEST_REQUESTED_SESSION_ID) == null);
    	String newSessionRequestAttr = (String) requestContainer.getServiceRequest().getAttribute(NEW_SESSION); // Zerbetto on 25-02-2008
    	isRequiredNewSession = newSessionRequestAttr != null && newSessionRequestAttr.equalsIgnoreCase("TRUE"); // Zerbetto on 25-02-2008
    } // if (session.isNew())
    synchronized (session) {
        RequestContainer parentRequestContainer = (RequestContainer) session
                .getAttribute(Constants.REQUEST_CONTAINER);
        if (!Navigator.isNavigatorEnabled()) {
            if (parentRequestContainer == null)
                requestContainer.setSessionContainer(new SessionContainer(true));
            else
                requestContainer.setSessionContainer(parentRequestContainer
                        .getSessionContainer());
        }
        else {
            if (parentRequestContainer == null)
                requestContainer.setSessionContainer(new SessionContainer(true));
            else {
                requestContainer.setSessionContainer(new SessionContainer(false));
                requestContainer.setParent(parentRequestContainer);
            } // if (parentRequestContainer == null) else
        } // if (!Navigator.isNavigatorEnabled())
        session.setAttribute(Constants.REQUEST_CONTAINER, requestContainer);
    } // synchronized (session)
    if (!isRequestedSessionIdValid) {
    	if (!isRequiredNewSession) { // Zerbetto on 25-02-2008
         TracerSingleton.log(Constants.NOME_MODULO, TracerSingleton.WARNING,
                 "AdapterHTTP::service: sessione scaduta !");
         throw new SessionExpiredException(EMFErrorSeverity.ERROR, "Expired Session");
    	} // Zerbetto on 25-02-2008
    } // if (!isRequestedSessionIdValid)
    // end modifications by Zerbetto on 25-02-2008: NEW_SESSION parameter can force a new session
}
 
Example 17
Source File: SessionTrackServlet.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	// 如果不存在 session 会话,则创建一个 session 对象
	HttpSession session = request.getSession(true);
	// 获取 session 创建时间
	Date createTime = new Date(session.getCreationTime());
	// 获取该网页的最后一次访问时间
	Date lastAccessTime = new Date(session.getLastAccessedTime());

	// 设置日期输出的格式
	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

	String title = "Servlet Session 实例";
	Integer visitCount = new Integer(0);
	String visitCountKey = new String("visitCount");
	String userIDKey = new String("userID");
	String userID = new String("admin");

	// 检查网页上是否有新的访问者
	if (session.isNew()) {
		session.setAttribute(userIDKey, userID);
	} else {
		visitCount = (Integer) session.getAttribute(visitCountKey);
		visitCount = visitCount + 1;
		userID = (String) session.getAttribute(userIDKey);
	}
	session.setAttribute(visitCountKey, visitCount);

	// 设置响应内容类型
	response.setContentType("text/html;charset=UTF-8");
	PrintWriter out = response.getWriter();

	String docType = "<!DOCTYPE html>\n";
	out.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n"
		+ "<body bgcolor=\"#f0f0f0\">\n" + "<h1 align=\"center\">" + title + "</h1>\n"
		+ "<h2 align=\"center\">Session 信息</h2>\n" + "<table border=\"1\" align=\"center\">\n"
		+ "<tr bgcolor=\"#949494\">\n" + "  <th>Session 信息</th><th>值</th></tr>\n" + "<tr>\n" + "  <td>id</td>\n"
		+ "  <td>" + session.getId() + "</td></tr>\n" + "<tr>\n" + "  <td>创建时间</td>\n" + "  <td>"
		+ df.format(createTime) + "  </td></tr>\n" + "<tr>\n" + "  <td>最后访问时间</td>\n" + "  <td>"
		+ df.format(lastAccessTime) + "  </td></tr>\n" + "<tr>\n" + "  <td>用户 ID</td>\n" + "  <td>" + userID
		+ "  </td></tr>\n" + "<tr>\n" + "  <td>访问统计:</td>\n" + "  <td>" + visitCount + "</td></tr>\n"
		+ "</table>\n" + "</body></html>");
}
 
Example 18
Source File: Response.java    From onedev with MIT License 4 votes vote down vote up
@Override
public void reset()
{
    _status = 200;
    _reason = null;
    _out.resetBuffer();
    _outputType = OutputType.NONE;
    _contentLength = -1;
    _contentType = null;
    _mimeType = null;
    _characterEncoding = null;
    _encodingFrom = EncodingFrom.NOT_SET;

    // Clear all response headers
    _fields.clear();

    // recreate necessary connection related fields
    for (String value : _channel.getRequest().getHttpFields().getCSV(HttpHeader.CONNECTION, false))
    {
        HttpHeaderValue cb = HttpHeaderValue.CACHE.get(value);
        if (cb != null)
        {
            switch (cb)
            {
                case CLOSE:
                    _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.CLOSE.toString());
                    break;
                case KEEP_ALIVE:
                    if (HttpVersion.HTTP_1_0.is(_channel.getRequest().getProtocol()))
                        _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.KEEP_ALIVE.toString());
                    break;
                case TE:
                    _fields.put(HttpHeader.CONNECTION, HttpHeaderValue.TE.toString());
                    break;
                default:
            }
        }
    }

    // recreate session cookies
    Request request = getHttpChannel().getRequest();
    HttpSession session = request.getSession(false);
    if (session != null && session.isNew())
    {
        SessionHandler sh = request.getSessionHandler();
        if (sh != null)
        {
            HttpCookie c = sh.getSessionCookie(session, request.getContextPath(), request.isSecure());
            if (c != null)
                addCookie(c);
        }
    }
}
 
Example 19
Source File: SecurityService.java    From live-chat-engine with Apache License 2.0 4 votes vote down vote up
public boolean initClientSessionForAcc(HttpServletRequest req, String accId) {
	
	String clientIp = getClientIp(req);
	String userAgent = getUserAgent(req);
	boolean isNewSession = false;
	
	HttpSession session = req.getSession(false);
	if(session == null){
		int maxSessionsCount = getMaxSessionsCountForChatClient(clientIp);
		int curSessionsByIp = c.sessionsCounter.getSessionsCount(clientIp);
		if(curSessionsByIp >= maxSessionsCount)
			throw new MaxSessionsCountByIpException(clientIp);
		
		session = req.getSession(true);
		if(session.isNew()){
			session.setMaxInactiveInterval(props.getIntVal(chats_sessionLivetime));	
			isNewSession = true;
		}
	}
	
	ClientSession clientSession = (ClientSession) session.getAttribute(CLIENT_INFO);
	if(clientSession == null){
		
		clientSession = new ClientSession(session.getId(), clientIp, userAgent);
		session.setAttribute(CLIENT_INFO, clientSession);
		
		clientSession.addAccId(accId);
		log.info("["+accId+"] "+"CLIENT session created: "
				+"ip="+clientIp
				+", userAgent="+userAgent
				+", sessionId="+session.getId());
		
	} else {
		
		boolean added = clientSession.addAccId(accId);
		if(added) {
			log.info("["+accId+"] "+"CLIENT session taken: "
					+"ip="+clientIp
					+", userAgent="+userAgent
					+", sessionId="+session.getId());
		}
	}
	
	return isNewSession;
	
}
 
Example 20
Source File: CsrfGuardFilter.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {

        //maybe the short circuit to disable is set
        if (!CsrfGuard.getInstance().isEnabled()) {
            filterChain.doFilter(request, response);
            return;
        }

        /** only work with HttpServletRequest objects **/
        if (request instanceof HttpServletRequest && response instanceof HttpServletResponse) {

            HttpServletRequest httpRequest = (HttpServletRequest) request;
            HttpSession session = httpRequest.getSession(false);

            //if there is no session and we arent validating when no session exists
            if (session == null && !CsrfGuard.getInstance().isValidateWhenNoSessionExists()) {
                // If there is no session, no harm can be done
                filterChain.doFilter(httpRequest, (HttpServletResponse) response);
                return;
            }

            CsrfGuard csrfGuard = CsrfGuard.getInstance();
            InterceptRedirectResponse httpResponse = new InterceptRedirectResponse((HttpServletResponse) response, httpRequest, csrfGuard);

//			 if(MultipartHttpServletRequest.isMultipartRequest(httpRequest)) {
//				 httpRequest = new MultipartHttpServletRequest(httpRequest);
//			 }

            if ((session != null && session.isNew()) && csrfGuard.isUseNewTokenLandingPage()) {
                csrfGuard.writeLandingPage(httpRequest, httpResponse);
            } else if (csrfGuard.isValidRequest(httpRequest, httpResponse)) {
                filterChain.doFilter(httpRequest, httpResponse);
            } else {
                /** invalid request - nothing to do - actions already executed **/
            }

            /** update tokens **/
            csrfGuard.updateTokens(httpRequest);

        } else {
            filterConfig.getServletContext().log(String.format("[WARNING] CsrfGuard does not know how to work with requests of class %s ", request.getClass().getName()));

            filterChain.doFilter(request, response);
        }
    }