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:SessionTracker.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    HttpSession session = req.getSession(true);

    Integer count = (Integer) session.getAttribute("count");

    if (count == null) {
        count = new Integer(1);
    } else {/*  w  ww.jav  a  2s  .com*/
        count = new Integer(count.intValue() + 1);
    }

    session.setAttribute("count", count);
    out.println("<html><head><title>SessionSnoop</title></head>");
    out.println("<body><h1>Session Details</h1>");
    out.println(
            "You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times.") + "<br/>");
    out.println("<h3>Details of this session:</h3>");
    out.println("Session id: " + session.getId() + "<br/>");
    out.println("New session: " + session.isNew() + "<br/>");
    out.println("Timeout: " + session.getMaxInactiveInterval() + "<br/>");
    out.println("Creation time: " + new Date(session.getCreationTime()) + "<br/>");
    out.println("Last access time: " + new Date(session.getLastAccessedTime()) + "<br/>");
    out.println("</body></html>");
}

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

@RequestMapping(value = "/products/store/{storeId}", method = RequestMethod.GET)
public String productsForStore(@PathVariable("storeId") Integer storeId, Model model, HttpSession session) {
    CartBean cart;/*from  w ww.  j  av  a2  s . co  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);

    List<Product> products = storeFacadeLocal.findProductsByStore(storeId);
    model.addAttribute("products", products);
    model.addAttribute("store", storeFacadeLocal.find(storeId));

    return "store";
}

From source file:com.br.uepb.controller.CadastroController.java

@RequestMapping(value = "/index/cadastrar.html", method = RequestMethod.POST)
public ModelAndView cadastrarPost(@ModelAttribute("loginDomain") LoginDomain login, Model model,
        HttpSession session) {

    LoginBusiness loginBusiness = new LoginBusiness();
    ModelAndView modelAndView = new ModelAndView();

    if (login != null) {
        if (loginBusiness.salvar(login)) {
            session.setAttribute("login", login.getLogin());
            SessaoBusiness sessao = new SessaoBusiness();
            sessao.setLoginDomain(login);
            GerenciarSessaoBusiness.addSessaoBusiness(login, sessao);
            modelAndView.setViewName("redirect:/home/home.html");

            modelAndView.setViewName("redirect:/home/home.html");
            String mensagem = "Cadastro realizado com sucesso";
            modelAndView.addObject("mensagem", mensagem);
            modelAndView.addObject("status", "0");
        } else {//from  w ww. j a v a  2 s .  c o  m
            modelAndView.setViewName("index/cadastrar");
            String mensagem = "Login j est sendo usado";
            modelAndView.addObject("mensagem", mensagem);
            modelAndView.addObject("status", "1");
        }
    }
    return modelAndView;
}

From source file:com.jspxcms.core.setup.SetupServlet.java

private void license(HttpServletRequest request, HttpServletResponse response) throws IOException {
    HttpSession session = request.getSession();
    session.setAttribute("step", 1);
}

From source file:org.openmrs.module.mclinic.web.controller.form.SyncLoggerController.java

@RequestMapping(value = "/module/mclinic/syncLog", method = RequestMethod.POST)
public String changeLogDate(HttpSession httpSession, @RequestParam(required = false) String logDate) {
    if (logDate != null && logDate.trim().length() > 0) {
        try {/*from   ww  w.  j a  v a2  s .c  o  m*/
            syncLogDate = df.parse(logDate);
        } catch (ParseException e) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Invalid date format");
            e.printStackTrace();
        }
    } else
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "No Date selected");
    return "redirect:syncLog.list";
}

From source file:org.openmrs.module.xformshelper.web.controller.SyncLoggerController.java

@RequestMapping(value = "/module/xformshelper/syncLog", method = RequestMethod.POST)
public String changeLogDate(HttpSession httpSession, @RequestParam(required = false) String logDate) {
    if (logDate != null && logDate.trim().length() > 0) {
        try {/*  w  w w .j  a  v a 2  s . co  m*/
            syncLogDate = df.parse(logDate);
        } catch (ParseException e) {
            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Invalid date format");
            e.printStackTrace();
        }
    } else
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "No Date selected");
    return "redirect:syncLog.list";
}

From source file:org.openmrs.web.controller.person.PersonAttributeTypeListController.java

/**
 * Moves the selected types down in the order
 * /* ww w . ja va2 s . co  m*/
 * @param personAttributeTypeId list of ids to move down
 * @param httpSession the current session
 * @should move selected ids down in the list
 * @should not fail if given last id
 * @should not fail if not given any ids
 */
@RequestMapping(method = RequestMethod.POST, params = "action=movedown")
public String moveDown(Integer[] personAttributeTypeId, HttpSession httpSession) {
    if (personAttributeTypeId == null) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PersonAttributeType.select");
    } else {
        PersonService ps = Context.getPersonService();
        List<PersonAttributeType> attributes = ps.getAllPersonAttributeTypes();

        // assumes attributes are returned in sortWeight order

        Set<PersonAttributeType> attributesToSave = new HashSet<PersonAttributeType>();

        List<Integer> selectedIds = Arrays.asList(personAttributeTypeId);

        for (int i = attributes.size() - 2; i >= 0; i--) {
            PersonAttributeType current = attributes.get(i);
            if (selectedIds.contains(current.getPersonAttributeTypeId())) {
                PersonAttributeType below = attributes.get(i + 1);

                // swap current and the attribute below it
                double temp = current.getSortWeight();
                current.setSortWeight(below.getSortWeight());
                below.setSortWeight(temp);
                Collections.swap(attributes, i, i + 1); // move the actual elements in the list as well

                attributesToSave.add(current);
                attributesToSave.add(below);
            }
        }

        // now save things
        for (PersonAttributeType pat : attributesToSave) {
            ps.savePersonAttributeType(pat);
        }
    }

    return "redirect:/admin/person/personAttributeType.list";
}

From source file:fi.hoski.web.auth.LoginServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setCharacterEncoding("UTF-8");

    response.setHeader("Cache-Control", "private, max-age=0, no-cache");
    String action = request.getParameter("action");
    try {/*from  ww w.  j a va 2 s .c o  m*/
        if (action == null || action.equals("login")) {
            // login

            String email = request.getParameter("email");
            String password = request.getParameter("password");
            email = (email != null) ? email.trim() : null;

            // 1. check params
            if (email == null || email.isEmpty() || password == null || password.isEmpty()) {
                log("email or password not ok");
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
            } else {
                // 2. check user exists
                Map<String, Object> user = userDirectory.authenticateUser(email, password);
                if (user == null) {
                    log("user not found");
                    response.sendError(HttpServletResponse.SC_FORBIDDEN);
                } else {
                    // 3. create session
                    HttpSession session = request.getSession(true);
                    session.setAttribute(USER, user);

                    response.getWriter().println("Logged in");
                }
            }
        } else {
            // logout

            HttpSession session = request.getSession(false);
            if (session != null) {
                session.setAttribute(USER, null);
                session.invalidate();
            }

            // change Cookie so that Vary: Cookie works
            Cookie c = new Cookie("JSESSIONID", null);
            c.setMaxAge(0);
            response.addCookie(c);

            response.getWriter().println("Logged out");
        }
    } catch (UnavailableException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    } catch (EmailNotUniqueException ex) {
        log(ex.getMessage(), ex);
        response.sendError(HttpServletResponse.SC_FORBIDDEN, ex.getMessage());
    }
}

From source file:com.impetus.kwitter.mb.LoginBean.java

public String authenticate() {
    String outcome = null;//  www  . j  a  v  a  2s  .  co  m

    // Validates Parameters
    if (StringUtils.isBlank(getUserName())) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter your user name"));
        outcome = Constants.OUTCOME_LOGIN_FAILED;
    }

    if (StringUtils.isBlank(getPassword())) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter password"));
        outcome = Constants.OUTCOME_LOGIN_FAILED;
    }

    if (StringUtils.isNotBlank(outcome)) {
        return outcome;
    } else {
        setTwitter(KwitterUtils.getTwitterService());

        User user = twitter.findUserById(getUserName());

        if (user == null) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Incorrect User Name"));
            outcome = Constants.OUTCOME_LOGIN_FAILED;
        } else if (user.getPersonalDetail().getPassword() == null
                || !user.getPersonalDetail().getPassword().equals(getPassword())) {
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Incorrect Password"));
            outcome = Constants.OUTCOME_LOGIN_FAILED;
        }

        if (StringUtils.isNotBlank(outcome)) {
            return outcome;
        } else {
            outcome = Constants.OUTCOME_LOGIN_SUCCESSFUL;
        }

        HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
                .getSession(true);
        session.setAttribute(Constants.USER_ID, getUserName());

        return outcome;
    }
}

From source file:org.openmrs.web.controller.person.PersonAttributeTypeListController.java

/**
 * Moves the selected types up one in the order
 * /*from   w  w  w .ja  v a  2 s .  co  m*/
 * @param personAttributeTypeId list of ids to move up
 * @param httpSession the current session
 * @should move selected ids up one in the list
 * @should not fail if given first id
 * @should not fail if not given any ids
 */
@RequestMapping(method = RequestMethod.POST, params = "action=moveup")
public String moveUp(Integer[] personAttributeTypeId, HttpSession httpSession) {
    if (personAttributeTypeId == null) {
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "PersonAttributeType.select");
    } else {
        PersonService ps = Context.getPersonService();

        List<PersonAttributeType> attributes = ps.getAllPersonAttributeTypes();

        Set<PersonAttributeType> attributesToSave = new HashSet<PersonAttributeType>();

        List<Integer> selectedIds = Arrays.asList(personAttributeTypeId);

        // assumes attributes are returned in sortWeight order

        for (int i = 1; i < attributes.size(); i++) {
            PersonAttributeType current = attributes.get(i);
            if (selectedIds.contains(current.getPersonAttributeTypeId())) {
                PersonAttributeType above = attributes.get(i - 1);

                // swap current and the attribute above it
                double temp = current.getSortWeight();
                current.setSortWeight(above.getSortWeight());
                above.setSortWeight(temp);
                Collections.swap(attributes, i, i - 1); // move the actual elements in the list as well

                attributesToSave.add(current);
                attributesToSave.add(above);
            }
        }

        // now save things
        for (PersonAttributeType pat : attributesToSave) {
            ps.savePersonAttributeType(pat);
        }
    }

    return "redirect:/admin/person/personAttributeType.list";
}