Example usage for javax.servlet.http HttpServletRequest getSession

List of usage examples for javax.servlet.http HttpServletRequest getSession

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletRequest getSession.

Prototype

public HttpSession getSession(boolean create);

Source Link

Document

Returns the current <code>HttpSession</code> associated with this request or, if there is no current session and <code>create</code> is true, returns a new session.

Usage

From source file:org.itracker.web.util.LoginUtilities.java

/**
 * Get a locale from request//from  ww w.j a  v a  2  s .  co m
 * <p/>
 * <p>
 * TODO the order of retrieving locale from request should be:
 * <ol>
 * <li>request-attribute Constants.LOCALE_KEY</li>
 * <li>request-param 'loc'</li>
 * <li>session attribute <code>Constants.LOCALE_KEY</code></li>
 * <li>cookie 'loc'</li>
 * <li>request.getLocale()/request.getLocales()</li>
 * <li>ITrackerResources.DEFAULT_LOCALE</li>
 * </ol>
 * </p>
 */
@SuppressWarnings("unchecked")
public static Locale getCurrentLocale(HttpServletRequest request) {
    Locale requestLocale = null;
    HttpSession session = request.getSession(true);
    try {

        requestLocale = (Locale) request.getAttribute(Constants.LOCALE_KEY);

        if (logger.isDebugEnabled()) {
            logger.debug("getCurrentLocale: request-attribute was {}", requestLocale);
        }

        if (null == requestLocale) {
            // get locale from request param
            String loc = request.getParameter("loc");
            if (null != loc && loc.trim().length() > 1) {
                requestLocale = ITrackerResources.getLocale(loc);
            }

            logger.debug("getCurrentLocale: request-parameter was {}", loc);

        }

        if (null == requestLocale) {
            // get it from the session
            requestLocale = (Locale) session.getAttribute(Constants.LOCALE_KEY);
            //            if (logger.isDebugEnabled()) {
            //               logger.debug("getCurrentLocale: session-attribute was "
            //                     + requestLocale);
            //            }
        }

        if (null == requestLocale) {
            ResourceBundle bundle = ITrackerResources.getBundle(request.getLocale());
            if (logger.isDebugEnabled()) {
                logger.debug("getCurrentLocale: trying request header locale " + request.getLocale());
            }
            if (bundle.getLocale().getLanguage().equals(request.getLocale().getLanguage())) {
                requestLocale = request.getLocale();
                if (logger.isDebugEnabled()) {
                    logger.debug("getCurrentLocale: request-locale was " + requestLocale);
                }
            }
        }

        // is there no way to detect supported locales of current
        // installation?

        if (null == requestLocale) {
            Enumeration<Locale> locales = (Enumeration<Locale>) request.getLocales();
            ResourceBundle bundle;
            Locale locale;
            while (locales.hasMoreElements()) {
                locale = locales.nextElement();
                bundle = ITrackerResources.getBundle(locale);

                logger.debug("getCurrentLocale: request-locales processing {}, bundle: {}", locale, bundle);

                if (bundle.getLocale().getLanguage().equals(locale.getLanguage())) {
                    requestLocale = locale;

                    logger.debug("getCurrentLocale: request-locales locale was {}", requestLocale);

                }
            }
        }

    } finally {
        if (null == requestLocale) {
            // fall back to default locale
            requestLocale = ITrackerResources.getLocale();

            logger.debug("getCurrentLocale: fallback default locale was {}", requestLocale);

        }
        session.setAttribute(Constants.LOCALE_KEY, requestLocale);
        request.setAttribute(Constants.LOCALE_KEY, requestLocale);
        request.setAttribute("currLocale", requestLocale);

        logger.debug("getCurrentLocale: request and session was setup with {}", requestLocale);

    }

    return requestLocale;
}

From source file:org.craftercms.engine.util.GroovyUtils.java

public static void addCommonVariables(Map<String, Object> variables, HttpServletRequest request,
        HttpServletResponse response, ServletContext servletContext) {
    variables.put(VARIABLE_APPLICATION, servletContext);
    variables.put(VARIABLE_REQUEST, request);
    variables.put(VARIABLE_RESPONSE, response);

    if (request != null) {
        variables.put(VARIABLE_PARAMS, HttpUtils.createRequestParamsMap(request));
        variables.put(VARIABLE_HEADERS, HttpUtils.createHeadersMap(request));
        variables.put(VARIABLE_COOKIES, HttpUtils.createCookiesMap(request));
        variables.put(VARIABLE_SESSION, request.getSession(false));
    } else {/*w  w w .j av a2s.  co m*/
        variables.put(VARIABLE_PARAMS, null);
        variables.put(VARIABLE_HEADERS, null);
        variables.put(VARIABLE_COOKIES, null);
        variables.put(VARIABLE_SESSION, null);
    }

    variables.put(VARIABLE_LOGGER, LOGGER);
    variables.put(VARIABLE_LOCALE, LocaleContextHolder.getLocale());

    addSiteConfigVariable(variables);
}

From source file:org.itracker.web.util.LoginUtilities.java

@Deprecated
public static boolean hasPermission(PermissionType[] permissionsNeeded, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    try {/*ww  w  .  jav a  2  s . c om*/
        UserDetails user = LoginUtilities.getPrincipal();

        HttpSession session = request.getSession(false);
        Map<Integer, Set<PermissionType>> permissions = (session == null) ? null
                : RequestHelper.getUserPermissions(session);
        return UserUtilities.hasPermission(permissions, permissionsNeeded);
    } catch (RuntimeException re) {
        logger.debug("hasPermission: failed to check permission", re);
        return false;
    }
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Determine the session id of the given request, if any.
 * @param request current HTTP request/* w  w w.  ja v  a 2  s  . co  m*/
 * @return the session id, or {@code null} if none
 */
public static String getSessionId(HttpServletRequest request) {
    Assert.notNull(request, "Request must not be null");
    HttpSession session = request.getSession(false);
    return (session != null ? session.getId() : null);
}

From source file:org.jruby.rack.mock.WebUtils.java

/**
 * Check the given request for a session attribute of the given name.
 * Returns null if there is no session or if the session has no such attribute.
 * Does not create a new session if none has existed before!
 * @param request current HTTP request// w ww.j a  v  a 2 s .  c  om
 * @param name the name of the session attribute
 * @return the value of the session attribute, or {@code null} if not found
 */
public static Object getSessionAttribute(HttpServletRequest request, String name) {
    Assert.notNull(request, "Request must not be null");
    HttpSession session = request.getSession(false);
    return (session != null ? session.getAttribute(name) : null);
}

From source file:com.redhat.rhn.frontend.taglibs.list.ListTagUtil.java

/**
 * Includes arbitrary _local_ url as content
 * @param ctx caller's page context//from w w w .  j av  a  2s.co m
 * @param url local url
 * @throws JspException if something goes wrong
 *
 * Note: Local means Urls in the same application
 */
public static void includeContent(PageContext ctx, String url) throws JspException {
    HttpServletRequest request = (HttpServletRequest) ctx.getRequest();
    HttpServletResponse response = (HttpServletResponse) ctx.getResponse();
    RequestDispatcher rd = request.getSession(true).getServletContext().getRequestDispatcher(url);
    if (rd == null) {
        ListTagUtil.write(ctx, "<!-- " + url + " not found -->");
    } else {
        try {
            BufferedResponseWrapper wrapper = new BufferedResponseWrapper(response);
            rd.include(request, wrapper);
            wrapper.flush();
            ListTagUtil.write(ctx, wrapper.getBufferedOutput());
        } catch (Exception e) {
            throw new JspException(e);
        }
    }
}

From source file:com.liusoft.dlog4j.UserLoginManager.java

/**
 * //from  ww w .  j a  v a  2  s.c o  m
 * 
 * @param req
 * @param res
 * @see com.liusoft.dlog4j.action.UserAction#doLogout(ActionMapping,
 *      ActionForm, HttpServletRequest, HttpServletResponse, String)
 */
public static void logoutUser(HttpServletRequest req, HttpServletResponse res) {
    // keep_days??
    SessionUserObject ubean = getLoginUser(req, res, false);
    if (ubean != null && ubean.getKeepDays() != 0) {
        DLOGUserManager.userLogout(ubean, true);
    }

    // Cookie
    RequestUtils.setCookie(req, res, COOKIE_UUID_KEY, "", 0);
    RequestUtils.setCookie(req, res, COOKIE_LASTLOGIN_KEY, "", 0);

    // session
    HttpSession ssn = req.getSession(false);
    if (ssn != null) {
        ssn.invalidate();
    }
}

From source file:edu.ucsb.nceas.metacat.util.RequestUtil.java

/**
 * Get the session data from a request. The Scenarios we can run across
 * here: /* www.  java 2s .c om*/
 * -- the session id parameter was set in the request parameters 
 * -- request.getSession returns a new session. There is a chance that the
 *    session id was set in a cookie. Check for a JSESSIONID cookie and use
 *    that id if provided. 
 * -- request.getSession returns a session that is a)
 *    preexisting or b) new but without a JSESSIONID cookie. Use the session id
 *    from this session
 * 
 * @param request
 *            the request from which to get the session data
 * @return the session data object representing the active session for this
 *         request. If there is no active session, the public session data
 *         is returned
 */
public static SessionData getSessionData(HttpServletRequest request) {
    SessionData sessionData = null;
    String sessionId = null;

    Hashtable<String, String[]> params = getParameters(request);

    if (params.containsKey("sessionid")) {
        // the session id is specified in the request parameters
        sessionId = ((String[]) params.get("sessionid"))[0];
        logMetacat.debug("session ID provided in request properties: " + sessionId);
    } else {
        HttpSession session = request.getSession(true);
        if (session.isNew()) {
            // this is a new session
            Cookie sessionCookie = RequestUtil.getCookie(request, "JSESSIONID");
            if (sessionCookie != null) {
                // and there is a JSESSIONID cookie
                sessionId = sessionCookie.getValue();
                logMetacat.debug("session ID provided in request cookie: " + sessionId);
            }
        }
        if (sessionId == null) {
            // there is an existing session (session is old)
            sessionId = session.getId();
            logMetacat.debug("session ID retrieved from request: " + sessionId);
        }
    }

    // if the session id is registered in SessionService, get the
    // SessionData for it. Otherwise, use the public session.
    if (SessionService.isSessionRegistered(sessionId)) {
        logMetacat.debug("retrieving session data from session service " + "for session id " + sessionId);
        sessionData = SessionService.getRegisteredSession(sessionId);
    } else {
        logMetacat.debug("using public session.  Given session id is " + "registered: " + sessionId);
        sessionData = SessionService.getPublicSession();
    }

    return sessionData;
}

From source file:fr.paris.lutece.portal.web.PortalJspBean.java

/**
 * Set the upload filter site next url/*from ww  w .j  a v a 2 s.  c  om*/
 * @param request the HTTP request
 */
public static void setUploadFilterSiteNextUrl(HttpServletRequest request) {
    String strNextUrl = request.getRequestURI();
    UrlItem url = new UrlItem(strNextUrl);
    Enumeration enumParams = request.getParameterNames();

    while (enumParams.hasMoreElements()) {
        String strParamName = (String) enumParams.nextElement();
        url.addParameter(strParamName, request.getParameter(strParamName));
    }

    HttpSession session = request.getSession(true);
    session.setAttribute(ATTRIBUTE_UPLOAD_FILTER_SITE_NEXT_URL, url.getUrl());
}

From source file:fr.paris.lutece.portal.web.PortalJspBean.java

/**
 * This method is called by Portal.jsp when it caught an
 * UserNotSignedException./*from w  w  w . ja  va 2  s.c  o  m*/
 * It gives the login url and stores in the session the url asked
 * @param request The HTTP request
 * @return The login page URL
 * @since v1.1
 */
public static String redirectLogin(HttpServletRequest request) {
    String strNextUrl = request.getRequestURI();
    UrlItem url = new UrlItem(strNextUrl);
    Enumeration enumParams = request.getParameterNames();

    while (enumParams.hasMoreElements()) {
        String strParamName = (String) enumParams.nextElement();
        url.addParameter(strParamName, request.getParameter(strParamName));
    }

    HttpSession session = request.getSession(true);
    session.setAttribute(ATTRIBUTE_LOGIN_NEXT_URL, url.getUrl());

    String strRedirect = SecurityService.getInstance().getLoginPageUrl();

    return AppPathService.getAbsoluteUrl(request, strRedirect);
}