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:com.lewischooman.services.EmployeeSrv.java

@Override
public boolean login(HttpSession httpSession, String uid, String password) {
    EmployeeDB employee = this.employeeDAO.getUserByLoginName(uid);
    if (employee != null && this.digester.digestToHex(password).equals(employee.getPassword())) {
        httpSession.setAttribute(Utility.LOGGED_IN_USER_ATTRIBUTE, employee);
        return true;
    } else {/*from   w ww .ja va  2s.  co m*/
        httpSession.removeAttribute(Utility.LOGGED_IN_USER_ATTRIBUTE);
        return false;
    }
}

From source file:com.benfante.minimark.controllers.AssessmentFillingController.java

@RequestMapping
@Validation(view = FORM_VIEW)/*ww  w.  ja  v a 2s .c  o  m*/
public String start(@ModelAttribute(ASSESSMENT_ATTR_NAME) AssessmentFilling assessmentFilling,
        BindingResult result, SessionStatus status, HttpServletRequest req, HttpSession session, Model model) {
    session.setAttribute(STUDENT_ID_ATTR_NAME, assessmentFilling.getIdentifier());
    AssessmentFilling prevFilling = assessmentFillingDao.findByAssessmentIdAndIdentifier(
            assessmentFilling.getAssessment().getId(), assessmentFilling.getIdentifier());
    if (prevFilling != null) { // this student already started this assessment
        model.addAttribute(ASSESSMENT_ATTR_NAME, prevFilling);
        FlashHelper.setRedirectError(req, "AssessmentAlreadyStarted");
        if (prevFilling.getSubmittedDate() != null) { // already submitted, return to the resul
            status.setComplete();
            logger.info(prevFilling.getLastName() + " " + prevFilling.getFirstName()
                    + " looked at the result of the assessment " + prevFilling.getId() + " (original:"
                    + prevFilling.getAssessment().getId() + ")");
            return "redirect:showResult.html?id=" + prevFilling.getId();
        } else { // return to the filling page
            logger.info(prevFilling.getLastName() + " " + prevFilling.getFirstName()
                    + " went again to fill the assessment " + prevFilling.getId() + " (original:"
                    + prevFilling.getAssessment().getId() + ")");
            return "redirect:fill.html";
        }
    } else {
        assessmentFilling.setLoggedIn(Boolean.TRUE);
        assessmentFilling.setStartDate(new Date());
        assessmentFillingDao.store(assessmentFilling);
        logger.info(assessmentFilling.getLastName() + " " + assessmentFilling.getFirstName()
                + " logged in assessment " + assessmentFilling.getId() + " (original:"
                + assessmentFilling.getAssessment().getId() + ")");
        return "redirect:fill.html";
    }
}

From source file:org.openmrs.module.iqchartimport.web.controller.MappingsController.java

@SuppressWarnings("unchecked")
@RequestMapping(method = RequestMethod.GET)
public String showPage(HttpServletRequest request, ModelMap model) throws IOException {
    Utils.checkSuperUser();//from  w  ww.java 2s  . c  o  m

    IQChartDatabase database = IQChartDatabase.getInstance();

    // If database is loaded then show drug mappings
    if (database != null) {
        IQChartSession session = new IQChartSession(database);

        // Get set of all ARV and TB drugs/regimens
        List<String> iqDrugs = session.getAllDrugs();

        ConceptClass drugClass = Context.getConceptService().getConceptClassByName("Drug");
        List<Concept> drugConcepts = Context.getConceptService().getConceptsByClass(drugClass);
        Map<String, List<Integer>> drugMappings = new HashMap<String, List<Integer>>();

        DrugMapping.load();

        for (String iqDrug : iqDrugs) {
            try {
                List<Integer> conceptIds = DrugMapping.getConcepts(iqDrug);
                drugMappings.put(iqDrug, conceptIds);
            } catch (IncompleteMappingException ex) {
            }
        }

        // Store the IQChart drug list in the session
        HttpSession httpSession = request.getSession();
        httpSession.setAttribute("iqDrugs", iqDrugs);

        model.put("database", IQChartDatabase.getInstance());
        model.put("drugConcepts", drugConcepts);
        model.put("iqDrugs", iqDrugs);
        model.put("drugMappings", drugMappings);

        session.close();
    }

    List<PatientIdentifierType> identifierTypes = Context.getPatientService().getAllPatientIdentifierTypes();
    List<Program> programs = Context.getProgramWorkflowService().getAllPrograms();
    List<Location> locations = Context.getLocationService().getAllLocations();

    String provList = Context.getAdministrationService()
            .getGlobalProperty(Constants.PROP_ADDRESS_ALL_PROVINCES);
    String[] allProvinces = provList != null ? provList.split(",") : new String[] {};

    model.put("identifierTypes", identifierTypes);
    model.put("allProvinces", allProvinces);
    model.put("programs", programs);
    model.put("locations", locations);
    model.put("mappings", Mappings.getInstance());
    model.put("encounterProvider", MappingUtils.getEncounterProvider());

    return "/module/iqchartimport/mappings";
}

From source file:MyServlet.java

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

    HttpSession session = req.getSession();

    Integer count = (Integer) session.getAttribute("tracker.count");
    if (count == null)
        count = new Integer(1);
    else/*from   w  ww.j  av a2  s  .  c  om*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("tracker.count", count);

    out.println("<HTML><HEAD><TITLE>SessionTracker</TITLE></HEAD>");
    out.println("<BODY><H1>Session Tracking Demo</H1>");

    out.println("You've visited this page " + count + ((count.intValue() == 1) ? " time." : " times."));

    out.println("<P>");

    out.println("<H2>Here is your session data:</H2>");
    Enumeration e = session.getAttributeNames();
    while (e.hasMoreElements()) {
        String name = (String) e.nextElement();
        out.println(name + ": " + session.getAttribute(name) + "<BR>");
    }
    out.println("</BODY></HTML>");
}

From source file:io.github.benas.todolist.web.servlet.user.LoginServlet.java

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

    String email = request.getParameter("email");
    String password = request.getParameter("password");

    LoginForm loginForm = new LoginForm();
    loginForm.setEmail(email);//ww w. j  a  va 2 s .  com
    loginForm.setPassword(password);

    String nextPage = LOGIN_PAGE;

    validateCredentials(request, loginForm);

    if (isInvalid(request)) {
        request.getRequestDispatcher(nextPage).forward(request, response);
        return;
    }

    if (isInvalidCombination(email, password)) {
        request.setAttribute("error", resourceBundle.getString("login.error.global.invalid"));
    } else {
        HttpSession session = request.getSession(true);//create session
        User user = userService.getUserByEmail(email);
        session.setAttribute(TodoListUtils.SESSION_USER, user);
        nextPage = "/todos";
    }
    request.getRequestDispatcher(nextPage).forward(request, response);
}

From source file:com.camel.action.base.LoginAction.java

public void userSet() {
    try {//from  w w  w .  ja  v  a 2s  . co m
        User userTmp = em.createNamedQuery("User.findUser", User.class).setParameter("email", user.getEmail())
                .getSingleResult();
        if (userTmp.getPassword().equals(user.getPassword())) {
            user = userTmp;
            HttpSession session = (HttpSession) FacesContext.getCurrentInstance().getExternalContext()
                    .getSession(true);
            session.setAttribute("user", user);
        }
    } catch (Exception e) {
        e.printStackTrace();
        Helper.addMessage("Kullanici bulunamad!");
    }
}

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

@Override
public boolean login(HttpSession httpSession, String uid, String password) {
    CustomerDB customer = this.customerDAO.getUserbyEmailId(uid);
    if (customer != null && this.digester.digestToHex(password).equals(customer.getPassword())) {
        httpSession.setAttribute(Utility.LOGGED_IN_USER_ATTRIBUTE, customer);
        return true;
    } else {/* www .  j a v  a2  s  .com*/
        httpSession.removeAttribute(Utility.LOGGED_IN_USER_ATTRIBUTE);
        return false;
    }
}

From source file:controller.servlet.ImportAmenities.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w w  w.ja  v a  2  s  .  co m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Obtencin de la regin
    String regionName = request.getParameter("regionname");

    boolean isXML = false;
    // Procesado del fichero para subirlo al servidor.
    for (Part part : request.getParts()) {
        if (part.getName().equals("file")) {
            try (InputStream is = request.getPart(part.getName()).getInputStream()) {
                int i = is.available();
                byte[] b = new byte[i];

                if (b.length == 0) {
                    break;
                }

                is.read(b);
                String fileName = obtenerNombreFichero(part);
                String extension = FilenameUtils.getExtension(fileName);
                String path = this.getServletContext().getRealPath("");
                String ruta = path + File.separator + Path.POIS_FOLDER + File.separator + fileName;
                File directory = new File(path + File.separator + Path.POIS_FOLDER);
                fileName = FilenameUtils.getBaseName(fileName);

                if (!directory.exists()) {
                    directory.mkdirs();
                }

                try (FileOutputStream os = new FileOutputStream(ruta)) {
                    os.write(b);
                }

                // Comprobacin de que sea un fichero xml.
                if (extension.equals("xml")) {
                    isXML = true;
                } else {
                    break;
                }

                if (isXML) {
                    // Crear entrada en la tabla de ficheros de PDIs.
                    UploadedPoiFileDaoImpl uPFDao = new UploadedPoiFileDaoImpl();
                    UploadedFile uFile = new UploadedFile();
                    uFile.setName(fileName);
                    uFile.setProcessedDate(new java.sql.Date(new java.util.Date().getTime()));
                    uPFDao.createFile(uFile);

                    // Almacenado de los datos en la Base de Datos.
                    NotifyingThread nT = new AmenityProcessing(ruta, regionName);
                    nT.addListener(this);
                    nT.setName(ThreadName.AMENITIES_THREAD_NAME);
                    nT.start();
                }
            }
        }
    }

    HttpSession session = request.getSession(true);
    session.setAttribute("isXML", isXML);

    if (!isXML) {
        session.setAttribute("error", true);
        String page = "/pages/amenitiesmanage.jsp";
        RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher(page);
        requestDispatcher.forward(request, response);
    } else {
        session.setAttribute("error", false);
        processRequest(request, response);
    }

}

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

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

    String email = request.getParameter("email");
    String activationKey = request.getParameter("activationKey");
    try {/* w  w w . j  a  v a  2 s.co m*/
        if (email != null && activationKey != null) {
            Map<String, Object> user = userDirectory.useActivationKey(email, activationKey);

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

            // redirect always, if user is not logged in,
            // there will be a login screen
            response.sendRedirect("/member"); //TODO target make configurable
        } else {
            HttpSession session = request.getSession(false);
            String etag = request.getHeader("If-None-Match");
            @SuppressWarnings("unchecked")
            Map<String, Object> user = (session != null) ? (Map<String, Object>) session.getAttribute(USER)
                    : null;
            String userEtag = getEtag(user);

            if (etag != null && etag.equals(userEtag)) {
                response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            } else {
                response.setHeader("ETag", userEtag);
                response.setHeader("Cache-Control", "private");
                response.setHeader("Vary", "Cookie");

                writeUserJSON(user, response);
            }
        }
    } 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.pearson.pdn.demos.chainoflearning.RegisterServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {

    String email = req.getParameter("email");
    if (email == null || !email.matches(EMAIL_PATTERN)) {
        res.sendRedirect(req.getContextPath() + "/register.jsp");
        return;// ww  w  .  j a  va2  s.  c  om
    }

    HttpSession session = req.getSession(true);

    // TODO - do this better. actually persist it...
    String verifyCode = Base64.encodeBase64String(String.valueOf(System.currentTimeMillis()).getBytes());
    session.setAttribute("auth", Base64.encodeBase64String((email + ":" + verifyCode).getBytes()));

    // TODO - actually send an email
    String linkParams = "?e=" + email + "&v=" + verifyCode;
    String emailContent = "Hello " + email + ",<br /><br /><a id=\"email-link\" href=\"./oauth2" + linkParams
            + "\">Link</a> your calendar with ChainOfLearning. <br/ > <br /> Thanks!";
    req.setAttribute("emailContent", emailContent);

    req.setAttribute("email", email);
    req.getRequestDispatcher("/activation.jsp").forward(req, res);
}