Example usage for javax.servlet.http HttpSession getAttribute

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

Introduction

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

Prototype

public Object getAttribute(String name);

Source Link

Document

Returns the object bound with the specified name in this session, or null if no object is bound under the name.

Usage

From source file:com.att.api.immn.controller.GetMsgController.java

public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    final HttpSession session = request.getSession();
    OAuthToken token = (OAuthToken) session.getAttribute("token");
    IMMNService srvc = new IMMNService(appConfig.getApiFQDN(), token);
    final String msgId = request.getParameter("getMsgId");

    /* TODO: convert nulls to the '-' character */
    JSONObject jresponse = new JSONObject();
    try {//from  w w  w  .  j av a  2s  .c om
        final Message msg = srvc.getMessage(msgId);
        final JSONArray tables = new JSONArray();
        final JSONArray values = new JSONArray().put(msg.getMessageId()).put(msg.getFrom())
                .put(msg.getRecipients()).put(msg.getText()).put(msg.getTimeStamp()).put(msg.isFavorite())
                .put(msg.isUnread()).put(msg.isIncoming()).put(msg.getType());
        tables.put(new JSONObject().put("caption", "Message:")
                .put("headers",
                        new JSONArray().put("Message ID").put("From").put("Recipients").put("Text")
                                .put("Timestamp").put("Favorite").put("Unread").put("Incoming").put("Type"))
                .put("values", new JSONArray().put(values)));
        jresponse.put("success", true).put("tables", tables);
    } catch (RESTException re) {
        jresponse.put("success", false).put("text", re.getMessage());
    }

    response.setContentType("text/html");
    PrintWriter writer = response.getWriter();
    writer.print(jresponse);
    writer.flush();
}

From source file:com.example.getstarted.basicactions.CreateBookServlet.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    assert ServletFileUpload.isMultipartContent(req);
    CloudStorageHelper storageHelper = (CloudStorageHelper) getServletContext().getAttribute("storageHelper");

    String newImageUrl = null;/*from www.  j ava2  s. co  m*/
    Map<String, String> params = new HashMap<String, String>();
    try {
        FileItemIterator iter = new ServletFileUpload().getItemIterator(req);
        while (iter.hasNext()) {
            FileItemStream item = iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), Streams.asString(item.openStream()));
            } else if (!Strings.isNullOrEmpty(item.getName())) {
                newImageUrl = storageHelper.uploadFile(item,
                        getServletContext().getInitParameter("bookshelf.bucket"));
            }
        }
    } catch (FileUploadException e) {
        throw new IOException(e);
    }

    String createdByString = "";
    String createdByIdString = "";
    HttpSession session = req.getSession();
    if (session.getAttribute("userEmail") != null) { // Does the user have a logged in session?
        createdByString = (String) session.getAttribute("userEmail");
        createdByIdString = (String) session.getAttribute("userId");
    }

    Book book = new Book.Builder().author(params.get("author")).description(params.get("description"))
            .publishedDate(params.get("publishedDate")).title(params.get("title"))
            .imageUrl(null == newImageUrl ? params.get("imageUrl") : newImageUrl).createdBy(createdByString)
            .createdById(createdByIdString).build();

    BookDao dao = (BookDao) this.getServletContext().getAttribute("dao");
    try {
        Long id = dao.createBook(book);
        logger.log(Level.INFO, "Created book {0}", book);
        resp.sendRedirect("/read?id=" + id.toString()); // read what we just wrote
    } catch (Exception e) {
        throw new ServletException("Error creating book", e);
    }
}

From source file:com.lewischooman.services.WebpageSrv.java

@Override
public UserDB getLoggedInUser(HttpSession httpSession) {
    return (UserDB) httpSession.getAttribute(Utility.LOGGED_IN_USER_ATTRIBUTE);
}

From source file:com.linecorp.sample.login.core.application.controller.WebController.java

@RequestMapping("/profile")
public ModelAndView profile(HttpSession httpSession) {
    AccessToken token = (AccessToken) httpSession.getAttribute(ACCESS_TOKEN);
    if (token == null) {
        return new ModelAndView("user/login");
    } else {//ww  w  .ja  v  a2 s  .co m
        Profile profile = lineAPIService.profile("Bearer", token.access_token);
        ModelAndView mav = new ModelAndView("user/profile");
        mav.addObject("profile", profile);
        return mav;
    }
}

From source file:eventmanager.controller.UserController.java

@RequestMapping(value = "/User/eventos")
public ModelAndView eventos(HttpSession session) {
    User user = (User) session.getAttribute("usuario_logado");
    ModelAndView modelAndView = new ModelAndView("menu");
    //Setando Parametros da Pagina        
    modelAndView.addObject("usuario", user.getNome());
    modelAndView.addObject("events", userDAO.getUserById(user.getIduser()).getMeusEventos());
    modelAndView.addObject("nomeEvento", new Busca());

    return RenderView.getInstance().renderEventosViewUser(user, modelAndView);
}

From source file:eventmanager.controller.UserController.java

@RequestMapping(value = "/User/menu")
public ModelAndView menu(HttpSession session) {
    User user = (User) session.getAttribute("usuario_logado");
    ModelAndView modelAndView = new ModelAndView("menu");
    //Setando Parametros da Pagina
    modelAndView.addObject("usuario", user.getNome());
    modelAndView.addObject("events", new EventDAO().getAllEvents());
    modelAndView.addObject("nomeEvento", new Busca());

    return RenderView.getInstance().renderMenuViewUser(user, modelAndView);
}

From source file:eventmanager.controller.UserController.java

@RequestMapping(value = "/User/inscricoes")
public ModelAndView inscricoes(HttpSession session) {
    User user = (User) session.getAttribute("usuario_logado");
    ModelAndView modelAndView = new ModelAndView("menu");
    //Setando Parametros da Pagina
    modelAndView.addObject("usuario", user.getNome());
    modelAndView.addObject("events", userDAO.getUserById(user.getIduser()).getMinhasInscricoes());
    modelAndView.addObject("nomeEvento", new Busca());

    return RenderView.getInstance().renderInscricoesViewUser(user, modelAndView);
}

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

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

    CartBean cart;// w  ww . j av a 2s  . co m
    if (session.getAttribute("cart") == null) {
        cart = new CartBean();
    } else {
        cart = (CartBean) session.getAttribute("cart");
        session.setAttribute("cart", cart);
    }

    List<Purchase> cartContents = ecomBeanFrontLocal.getCartContents(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 = productFacadeLocal.findProductsByNameLike("%" + keywords + "%");
    products.addAll(productFacadeLocal.findProductsByDescriptionLike("%" + keywords + "%"));

    model.addAttribute("products", products);
    model.addAttribute("keywords", keywords);

    return "search";
}

From source file:net.sourceforge.vulcan.web.PreferencesFilter.java

private void setupPreferences(HttpServletRequest request) {
    final HttpSession session = request.getSession(false);

    if (session != null && session.getAttribute(Keys.PREFERENCES) != null) {
        return;//w  w w.  j  av  a2s. c o m
    }

    final PreferencesDto prefs;

    final String cookieData = getCookieData(request, Keys.PREFERENCES);

    if (cookieData == null) {
        prefs = store.getDefaultPreferences();
    } else {
        prefs = store.convertFromString(cookieData);
    }

    if (session == null) {
        request.setAttribute(Keys.PREFERENCES, prefs);
    } else if (session.getAttribute(Keys.PREFERENCES) == null) {
        session.setAttribute(Keys.PREFERENCES, prefs);
    }
}

From source file:com.ec2box.common.interceptor.CSRFInterceptor.java

@Override
protected String handleToken(ActionInvocation invocation) throws Exception {
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession session = request.getSession(true);
    synchronized (session) {
        String sessionToken = (String) session.getAttribute(AuthUtil.CSRF_TOKEN_NM);
        String token = request.getParameter(AuthUtil.CSRF_TOKEN_NM);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(sessionToken) || !token.equals(sessionToken)) {
            AuthUtil.deleteAllSession(session);
            return this.handleInvalidToken(invocation);
        }//  w w w.j  ava  2s.c o m

        //generate new token upon post
        if ("POST".equals(request.getMethod()) && !request.getContentType().contains("multipart/form-data")) {
            AuthUtil.generateCSRFToken(session);
        }
    }

    return this.handleValidToken(invocation);
}