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:controller.NotificationsController.java

@RequestMapping(value = "notifications", method = RequestMethod.GET)
public ModelAndView handleNotifs(HttpServletRequest request) {
    HttpSession session = request.getSession();
    if (session == null || !request.isRequestedSessionIdValid()) {
        return new ModelAndView("index");
    }/*w w w.  j  ava 2  s.c  o  m*/

    session.setAttribute("currentPage", "/notifications.htm");

    // Get all the notifications sent to this user
    UsersEntity user = (UsersEntity) session.getAttribute("user");
    ArrayList<NotificationsEntity> notifs = this.notifsService.searchByTarget(user);
    ModelAndView mv = new ModelAndView("notifications");
    mv.addObject("currentUser", user);
    mv.addObject("notifs", notifs);
    mv.addObject("nbNotifs", notifs.size());

    return mv;
}

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

@RequestMapping(value = "/stores", method = RequestMethod.GET)
public String stores(Model model, HttpSession session) {
    CartBean cart;//from  w  w  w.  ja va  2  s. c om
    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);

    model.addAttribute("stores", storeFacadeLocal.findAll());

    return "stores";
}

From source file:org.mashupmedia.controller.remote.RemoteLibraryController.java

protected void logInAsSystemuser(HttpServletRequest request) {

    User systemUser = adminManager.getSystemUser();
    UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
            systemUser.getUsername(), systemUser.getPassword());

    // Authenticate the user
    Authentication authentication = authenticationManager.authenticate(authRequest);
    SecurityContext securityContext = SecurityContextHolder.getContext();
    securityContext.setAuthentication(authentication);

    // Create a new session and add the security context.
    HttpSession session = request.getSession(true);
    session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
}

From source file:org.openmrs.module.sdmxhdintegration.web.controller.MessageUploadFormController.java

/**
 * Handles form submission/*from   w  ww.j a v  a2s .c  o  m*/
 * @param request the request
 * @param message the message
 * @param result the binding result
 * @param status the session status
 * @return the view
 * @throws IllegalStateException
 */
@RequestMapping(method = RequestMethod.POST)
public String handleSubmission(HttpServletRequest request, @ModelAttribute("message") SDMXHDMessage message,
        BindingResult result, SessionStatus status) throws IllegalStateException {

    DefaultMultipartHttpServletRequest req = (DefaultMultipartHttpServletRequest) request;
    MultipartFile file = req.getFile("sdmxhdMessage");
    File destFile = null;

    if (!(file.getSize() <= 0)) {
        AdministrationService as = Context.getAdministrationService();
        String dir = as.getGlobalProperty("sdmxhdintegration.messageUploadDir");
        String filename = file.getOriginalFilename();
        filename = "_" + (new SimpleDateFormat("yyyy-MM-dd'T'HH-mm-ss")).format(new Date()) + "_" + filename;
        destFile = new File(dir + File.separator + filename);
        destFile.mkdirs();

        try {
            file.transferTo(destFile);
        } catch (IOException e) {
            HttpSession session = request.getSession();
            session.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                    "Could not save file. Make sure you have setup the upload directory using the configuration page and that the directory is readable by the tomcat user.");
            return "/module/sdmxhdintegration/messageUpload";
        }

        message.setZipFilename(filename);
    }

    new SDMXHDMessageValidator().validate(message, result);

    if (result.hasErrors()) {
        log.error("SDMXHDMessage object failed validation");
        if (destFile != null) {
            destFile.delete();
        }
        return "/module/sdmxhdintegration/messageUpload";
    }

    SDMXHDService service = Context.getService(SDMXHDService.class);
    ReportDefinitionService rds = Context.getService(ReportDefinitionService.class);
    service.saveMessage(message);

    // delete all existing mappings and reports
    List<KeyFamilyMapping> allKeyFamilyMappingsForMsg = service.getKeyFamilyMappingsFromMessage(message);
    for (Iterator<KeyFamilyMapping> iterator = allKeyFamilyMappingsForMsg.iterator(); iterator.hasNext();) {
        KeyFamilyMapping kfm = iterator.next();
        Integer reportDefinitionId = kfm.getReportDefinitionId();
        service.deleteKeyFamilyMapping(kfm);
        if (reportDefinitionId != null) {
            rds.purgeDefinition(rds.getDefinition(reportDefinitionId));
        }
    }

    // create initial keyFamilyMappings
    try {
        DSD dsd = Utils.getDataSetDefinition(message);
        List<KeyFamily> keyFamilies = dsd.getKeyFamilies();
        for (Iterator<KeyFamily> iterator = keyFamilies.iterator(); iterator.hasNext();) {
            KeyFamily keyFamily = iterator.next();

            KeyFamilyMapping kfm = new KeyFamilyMapping();
            kfm.setKeyFamilyId(keyFamily.getId());
            kfm.setMessage(message);
            service.saveKeyFamilyMapping(kfm);
        }
    } catch (Exception e) {
        log.error("Error parsing SDMX-HD Message: " + e, e);
        if (destFile != null) {
            destFile.delete();
        }

        service.deleteMessage(message);
        result.rejectValue("sdmxhdZipFileName", "upload.file.rejected",
                "This file is not a valid zip file or it does not contain a valid SDMX-HD DataSetDefinition");
        return "/module/sdmxhdintegration/messageUpload";
    }

    return "redirect:messages.list";
}

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

@RequestMapping(value = "/")
public String home(Model model, HttpSession session) {
    CartBean cart;/*  w  w w.  j a  v  a 2s  .com*/
    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);

    model.addAttribute("products", productFacadeLocal.findAll());

    return "home";
}

From source file:com.banyou.backend.web.front.SearchController.java

@RequestMapping(value = { "toList" }, method = RequestMethod.GET)
public String toList(HttpSession session, @RequestParam(value = "dest", required = false) List<Long> destIds) {
    if (CollectionUtils.isEmpty(destIds)) {
        destIds = Collections.emptyList();
    }/*w  w  w .j av  a  2  s.co m*/
    session.setAttribute(DEST_CODE, destIds.toArray(new Long[0]));
    return "redirect:/front/search/list";
}

From source file:egpi.tes.ahv.servicio.AutenticacionREST.java

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

    try {/*from w w w . ja va  2  s.  c o m*/

        AutenticacionVO authVO = new AutenticacionVO();
        authVO.setPassword(request.getParameter("pass"));
        authVO.setUsername(request.getParameter("user"));
        autenticacionUsuarioLogin(authVO);

        HttpSession session = request.getSession(true);
        session.setAttribute("clientjasper", this.client);
        session.setAttribute("propiedadesjasper", this.properties);
        session.setAttribute("authVO", authVO);

        PrintWriter out = response.getWriter();
        out.println(obj);

    } catch (Exception e) {
        e.printStackTrace();
        procesarError(response, e);
    }

}

From source file:com.cme.hr.controller.PersonController.java

@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createNewPerson(@ModelAttribute Person person, BindingResult result,
        final RedirectAttributes redirectAttributes, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    if (result.hasErrors()) {
        System.out.println("soy el error " + result.toString());
        ModelAndView mav = new ModelAndView("person-new", "person", person);
        initSelect(mav);/*w  w  w .  j a v  a 2 s  .  c o  m*/
        return mav;
    }

    personService.create(person);
    Integer p = person.getIdPerson();
    HttpSession session = request.getSession(true);
    session.setAttribute("id_Person", p);

    ModelAndView mav = new ModelAndView("redirect:/background/create.html");

    return mav;
}

From source file:org.davidmendoza.esu.web.EstudiaController.java

@RequestMapping(value = "/{anio}/{trimestre}/{leccion}/{dia}")
public String leccion(Model model, @ModelAttribute Inicio inicio, HttpSession session, TimeZone timeZone) {

    session.setAttribute("anio", inicio.getAnio());
    session.setAttribute("trimestre", inicio.getTrimestre());
    session.setAttribute("leccion", inicio.getLeccion());
    session.setAttribute("dia", inicio.getDia());

    log.info("Estudia: {} : {} : {} : {}", inicio.getAnio(), inicio.getTrimestre(), inicio.getLeccion(),
            inicio.getDia());//from w ww .j  a v a2 s  . c om

    inicio = inicioService.inicio(inicio);

    Inicio hoy = inicioService.inicio(timeZone);
    if (inicio.getAnio().equals(hoy.getAnio()) && inicio.getTrimestre().equals(hoy.getTrimestre())
            && inicio.getLeccion().equals(hoy.getLeccion()) && inicio.getDia().equals(hoy.getDia())) {
        inicio.setEsHoy(Boolean.TRUE);
    } else {
        StringBuilder sb = new StringBuilder();
        sb.append("/estudia");
        sb.append("/").append(hoy.getAnio());
        sb.append("/").append(hoy.getTrimestre());
        sb.append("/").append(hoy.getLeccion());
        sb.append("/").append(hoy.getDia());
        inicio.setHoyLiga(sb.toString());
        inicio.setEsHoy(Boolean.FALSE);
    }

    Publicacion publicacion = inicio.getPublicacion();
    if (publicacion != null) {
        publicacion.getArticulo().setVistas(publicacionService.agregarVista(publicacion.getArticulo()));

        model.addAttribute("estudia", inicio);
        model.addAttribute("ayer", inicioService.ayer(inicio));
        model.addAttribute("manana", inicioService.manana(inicio));

        return "estudia/leccion";
    } else {
        return "redirect:/";
    }
}

From source file:br.com.arduinoweb.controller.AndroidController.java

private void setSession(HttpSession session, Login login) {
    if (login.isArduino()) {
        session.setAttribute("conexao", "btn-success");
    } else {/*w  ww  .j  a v a2s .  c  om*/
        session.setAttribute("conexao", "btn-danger");
    }
}