Example usage for javax.servlet.http HttpSession setAttribute

List of usage examples for javax.servlet.http HttpSession setAttribute

Introduction

In this page you can find the example usage for javax.servlet.http HttpSession setAttribute.

Prototype

public void setAttribute(String name, Object value);

Source Link

Document

Binds an object to this session, using the name specified.

Usage

From source file:miage.ecom.web.controller.CategoryController.java

@RequestMapping(value = "/categories", method = RequestMethod.GET)
public String categories(Model model, HttpSession session) {

    CartBean cart;//from  ww  w .  jav a  2s.  c o m
    if (session.getAttribute("cart") == null) {
        cart = new CartBean();
    } else {
        cart = (CartBean) session.getAttribute("cart");
        session.setAttribute("cart", cart);
    }

    model.addAttribute("cartTotalValue", ecomBeanFrontLocal.getTotalValue(cart));
    model.addAttribute("nbProducts", ecomBeanFrontLocal.getCartContents(cart).size());

    List<Category> categories = categoryFacade.findAll();
    model.addAttribute("categories", categories);

    return "categories";
}

From source file:net.anthonychaves.bookmarks.web.ApiKeyController.java

@RequestMapping(method = RequestMethod.POST)
public String generateApiKey(HttpSession session, ModelMap model) {
    User user = (User) session.getAttribute("user");
    String apiKey = UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16).toUpperCase();
    user = userService.setApiKey(user, apiKey);
    session.setAttribute("user", user);

    model.addAttribute("status", "success");
    model.addAttribute("newKey", apiKey);

    return "redirect:user";
}

From source file:iddb.web.security.service.CommonUserService.java

protected void createUserSession(HttpServletRequest request, HttpServletResponse response, Subject subject,
        boolean persistent) {
    HttpSession session = request.getSession(true);
    session.setAttribute(UserService.SUBJECT, subject);
    saveLocal(subject);/*from  w w  w.  j a  v  a2s  .c  om*/
    String sessionKey = HashUtils.generate(subject.getLoginId());
    session.setAttribute(UserService.SESSION_KEY, sessionKey);
    Cookie cookieKey = new Cookie("iddb-k", sessionKey);
    Cookie cookieUser = new Cookie("iddb-u", subject.getKey().toString());
    cookieKey.setPath(request.getContextPath() + "/");
    cookieUser.setPath(request.getContextPath() + "/");
    if (persistent) {
        cookieKey.setMaxAge(COOKIE_EXPIRE_REMEMBER);
        cookieUser.setMaxAge(COOKIE_EXPIRE_REMEMBER);
    } else {
        cookieKey.setMaxAge(-1);
        cookieUser.setMaxAge(-1);
    }
    response.addCookie(cookieKey);
    response.addCookie(cookieUser);

    log.trace("Create new session {}, {}, {}",
            new String[] { sessionKey, subject.getKey().toString(), request.getRemoteAddr() });
    createSession(sessionKey, subject.getKey(), request.getRemoteAddr());

}

From source file:com.eftech.wood.controllers.ControllerCartPhone.java

@RequestMapping(value = "/basket", method = RequestMethod.GET)
public String cart(HttpSession session) {

    ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
    if (cart == null)
        cart = new ShoppingCart();
    cart.calculateTotal("0"); // GDP (for example)
    session.setAttribute("cart", cart);
    session.setAttribute("page", "basket"); //

    return "ru_cart";
}

From source file:com.r3bl.controller.LoginController.java

@RequestMapping("efetuaLogin")
public String efetuaLogin(Usuario u, HttpSession session, RedirectAttributes red) {
    try {//from   www.  ja  va2s.c o m
        u = usuarioService.getUsuarioByName(u.getNome());
        if (usuarioService.userExists(u.getNome(), u.getSenha()) && !u.getTipo().equals("PACIENTE")) {
            session.setAttribute("usuarioLogado", u);
            System.out.println("Criei atributo usuarioLogado: " + u.getNome() + " " + u.getTipo());
            return "bem-vindo";
        }

    } catch (Exception ex) {
        Logger.getLogger(LoginController.class.getName()).log(Level.SEVERE, null, ex);
    }
    red.addFlashAttribute("invalido", true);
    return "redirect:login";
}

From source file:com.onehippo.gogreen.login.HstConcurrentLoginFilter.java

private void registerUserSession(HttpServletRequest request, String username) {
    log.debug("HstConcurrentLoginFilter will register session for {}", username);
    HttpSession session = request.getSession();
    session.setAttribute(USERNAME_ATTR, username);

    ServletContext servletContext = session.getServletContext();
    @SuppressWarnings("unchecked")
    Map<String, HttpSessionWrapper> map = (Map<String, HttpSessionWrapper>) servletContext
            .getAttribute(USERNAME_SESSIONID_MAP_ATTR);

    if (map != null) {
        String newSessionId = session.getId();
        HttpSessionWrapper oldHttpSessionWrapper = map.put(username,
                new HttpSessionWrapper(session, earlySessionInvalidation));
        log.debug("HstConcurrentLoginFilter registered session ({}) for {}.", newSessionId, username);

        if (oldHttpSessionWrapper != null) {
            oldHttpSessionWrapper.invalidate();
            log.debug("HstConcurrentLoginFilter kicked out session ({}) for {}.", oldHttpSessionWrapper.getId(),
                    username);/* w  w w . j a  v  a  2s.c o m*/
        }
    } else {
        log.error("HstConcurrentLoginFilter is in invalid state. The session ids map is not found.");
    }
}

From source file:com.salesmanager.core.module.impl.application.logon.CustomerJAASLogonImpl.java

private boolean isValidLogin(HttpServletRequest req, String username, String password, int merchantId) {
    LoginContext context = null;//from w  ww.  ja  v a  2 s  . c o m
    try {

        // 1) using jaas.conf
        // context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME,new
        // CustomerLoginCallBackHandler(username,password));

        // 2) programaticaly created jaas.conf equivalent
        SalesManagerJAASConfiguration jaasc = new SalesManagerJAASConfiguration(
                "com.salesmanager.core.module.impl.application.logon.JAASSecurityCustomerLoginModule");
        context = new LoginContext(LOGIN_CONTEXT_CONFIG_NAME, null,
                new CustomerLoginCallBackHandler(username, password, merchantId), jaasc);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException("Unable to Create Login Context, configuration file may be missing", e);
        /**
         * needs a jaas.conf file in the startup script Logon {
         * com.salesmanager.core.module.impl.application.logon.
         * JAASSecurityCustomerLoginModule required; }; and this parameter
         * -Djava.security.auth.login.config=jaas.conf
         */
    }
    if (context != null) {
        try {
            context.login();

            Subject s = context.getSubject();

            if (s != null) {
                Set principals = s.getPrincipals();
            }

            // Create a principal
            UserPrincipal principal = new UserPrincipal(username);

            HttpSession session = req.getSession();
            session.setAttribute("PRINCIPAL", principal);
            session.setAttribute("LOGINCONTEXT", context);

            return true;
        } catch (LoginException e) {
            e.printStackTrace();
            return false;
        }
    }
    return false;
}

From source file:cz.strmik.cmmitool.web.controller.AppraisalController.java

@RequestMapping(method = RequestMethod.POST, value = "/")
public String selectProject(ModelMap model, @RequestParam("projectId") String projectId, HttpSession session) {
    if (projectId != null) {
        Project project = projectDao.read(projectId);
        if (project != null) {
            model.addAttribute(Attribute.PROJECT, project);
            session.setAttribute(Attribute.PROJECT, project);
            projectRolesToSession(model, project);
        } else {/*from  ww w. jav a  2  s . c  o m*/
            log.warn("Project with id =" + projectId + " not found!");
        }
    }
    return DASHBOARD;
}

From source file:net.anthonychaves.bookmarks.web.BookmarkController.java

@RequestMapping(method = RequestMethod.DELETE)
public String deleteBookmark(@RequestParam(value = "bookmarkId") String bookmarkId, HttpSession session,
        ModelMap model) {/* w ww  .j av  a  2s .  c  o m*/

    User user = (User) session.getAttribute("user");
    user = userService.deleteBookmark(user, bookmarkId);
    session.setAttribute("user", user);

    model.clear();
    model.addAttribute("result", bookmarkId);

    return "redirect:/b/user";
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.actions.EditJoinExpAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.//  www . j  a  v a2s  .co  m
 *
 * @param mapping The ActionMapping used to select this instance
 * @param actionForm The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    MessageResources messages = getResources(request);
    HttpSession session = request.getSession();

    if ("request".equals(mapping.getScope())) {
        request.setAttribute(mapping.getAttribute(), form);
    } else {
        session.setAttribute(mapping.getAttribute(), form);
    }

    if (!isClient(session)) {
        session.setAttribute("joiningExp", new Boolean(true));
        return (mapping.findForward("login_fail"));
    }

    int clientId = this.getClientId(session);
    String name = ControlServ.dbw.getSubjNameById(clientId);

    if (name != null) {
        session.setAttribute("clientName", name);
    } else {
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.client.notRegistered"));
        saveErrors(request, errors);
        return (mapping.findForward("login_fail"));
    }

    return (mapping.findForward("success"));
}