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:org.openmrs.web.controller.user.ChangePasswordFormController.java

/**
 * This method will display the change password form
 * //from  ww  w  .  j  av  a 2s  .c o  m
 * @param httpSession current browser session
 * @return the view to be rendered
 */
@RequestMapping(method = RequestMethod.GET)
public String showForm(HttpSession httpSession) {
    httpSession.setAttribute(WebConstants.OPENMRS_HEADER_USE_MINIMAL, "false");
    httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "User.password.change");
    return "/module/legacyui/admin/users/changePasswordForm";
}

From source file:de.blizzy.documentr.web.filter.AuthenticationCreationTimeFilter.java

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    int hashCode = getHashCode(authentication);

    HttpSession session = ((HttpServletRequest) request).getSession();
    Integer lastAuthenticationHashCode = (Integer) session.getAttribute(AUTHENTICATION_HASH_CODE);
    if ((lastAuthenticationHashCode == null) || (lastAuthenticationHashCode != hashCode)) {
        session.setAttribute(AUTHENTICATION_HASH_CODE, hashCode);
        AuthenticationUtil.setAuthenticationCreationTime(session, System.currentTimeMillis());
    }/* w  w w .j  av  a2 s.  c om*/

    chain.doFilter(request, response);
}

From source file:id.ac.ipb.ilkom.training.controller.LoginController.java

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(HttpSession session, Model model) {
    String errorMessage = (String) session.getAttribute("errorMessage");
    if (errorMessage != null && errorMessage.trim().length() > 0) {
        model.addAttribute("errorMessage", errorMessage);
        //remove attribute from session
        session.setAttribute("errorMessage", null);
        session.removeAttribute("errorMessage");
    }/*from ww w  . j  ava2  s  .c o m*/
    return "login";
}

From source file:org.openmrs.web.controller.form.AuditFieldController.java

/**
 * The onSubmit function receives the form/command object that was modified by the input form
 * and saves it to the db//  w  w w  . j a v a  2 s.  c  o  m
 * 
 * @see org.springframework.web.servlet.mvc.SimpleFormController#onSubmit(javax.servlet.http.HttpServletRequest,
 *      javax.servlet.http.HttpServletResponse, java.lang.Object,
 *      org.springframework.validation.BindException)
 */
@Override
protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object obj,
        BindException errors) throws Exception {

    HttpSession httpSession = request.getSession();

    String view = getFormView();

    if (Context.isAuthenticated()) {
        view = getSuccessView();

        try {
            int i = Context.getFormService().mergeDuplicateFields();
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ARGS, i);
            httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR, "Form.auditSuccess");
        } catch (APIException e) {
            log.warn("Error in mergeDuplicateFields", e);

            httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR, "Form.auditError");
        }
    }

    return new ModelAndView(new RedirectView(view));
}

From source file:contestWebsite.ContactUs.java

@Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    Query query = new Query("user")
            .setFilter(new FilterPredicate("name", FilterOperator.EQUAL, req.getParameter("name")));
    List<Entity> users = datastore.prepare(query).asList(FetchOptions.Builder.withLimit(3));
    Entity feedback = new Entity("feedback");
    if (users.size() != 0) {
        feedback.setProperty("user-id", users.get(0).getProperty("user-id"));
    }//w w  w  .  j a v  a  2  s .c om

    String name = escapeHtml4(req.getParameter("name"));
    String school = escapeHtml4(req.getParameter("school"));
    String comment = escapeHtml4(req.getParameter("text"));
    String email = escapeHtml4(req.getParameter("email"));

    HttpSession sess = req.getSession(true);
    sess.setAttribute("name", name);
    sess.setAttribute("school", school);
    sess.setAttribute("email", email);
    sess.setAttribute("comment", comment);

    Entity contestInfo = Retrieve.contestInfo();
    if (!(Boolean) sess.getAttribute("nocaptcha")) {
        URL reCaptchaURL = new URL("https://www.google.com/recaptcha/api/siteverify");
        String charset = java.nio.charset.StandardCharsets.UTF_8.name();
        String reCaptchaQuery = String.format("secret=%s&response=%s&remoteip=%s",
                URLEncoder.encode((String) contestInfo.getProperty("privateKey"), charset),
                URLEncoder.encode(req.getParameter("g-recaptcha-response"), charset),
                URLEncoder.encode(req.getRemoteAddr(), charset));

        final URLConnection connection = new URL(reCaptchaURL + "?" + reCaptchaQuery).openConnection();
        connection.setRequestProperty("Accept-Charset", charset);
        String response = CharStreams.toString(CharStreams.newReaderSupplier(new InputSupplier<InputStream>() {
            @Override
            public InputStream getInput() throws IOException {
                return connection.getInputStream();
            }
        }, Charsets.UTF_8));

        try {
            JSONObject JSONResponse = new JSONObject(response);
            if (!JSONResponse.getBoolean("success")) {
                resp.sendRedirect("/contactUs?captchaError=1");
                return;
            }
        } catch (JSONException e) {
            e.printStackTrace();
            resp.sendRedirect("/contactUs?captchaError=1");
            return;
        }
    }

    feedback.setProperty("name", name);
    feedback.setProperty("school", school);
    feedback.setProperty("email", email);
    feedback.setProperty("comment", new Text(comment));
    feedback.setProperty("resolved", false);

    Transaction txn = datastore.beginTransaction();
    try {
        datastore.put(feedback);
        txn.commit();

        Session session = Session.getDefaultInstance(new Properties(), null);
        String appEngineEmail = (String) contestInfo.getProperty("account");

        try {
            Message msg = new MimeMessage(session);
            msg.setFrom(new InternetAddress(appEngineEmail, "Tournament Website Admin"));
            msg.addRecipient(Message.RecipientType.TO,
                    new InternetAddress((String) contestInfo.getProperty("email"), "Contest Administrator"));
            msg.setSubject("Question about tournament from " + name);
            msg.setReplyTo(new InternetAddress[] { new InternetAddress(req.getParameter("email"), name),
                    new InternetAddress(appEngineEmail, "Tournament Website Admin") });

            VelocityEngine ve = new VelocityEngine();
            ve.init();

            VelocityContext context = new VelocityContext();
            context.put("name", name);
            context.put("email", email);
            context.put("school", school);
            context.put("message", comment);

            StringWriter sw = new StringWriter();
            Velocity.evaluate(context, sw, "questionEmail",
                    ((Text) contestInfo.getProperty("questionEmail")).getValue());
            msg.setContent(sw.toString(), "text/html");
            Transport.send(msg);
        } catch (MessagingException e) {
            e.printStackTrace();
            resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
            return;
        }

        resp.sendRedirect("/contactUs?updated=1");
        sess.invalidate();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
    } finally {
        if (txn.isActive()) {
            txn.rollback();
        }
    }
}

From source file:de.innovationgate.wgpublisher.webtml.portlet.TMLPortlet.java

/**
 * Queue that stores the last 1000 fired portlet events, so portlets can
 * react on them with serverside code./*from w  ww.  ja  v a2s . c om*/
 * @param session
 * @return
 */
public static LinkedMap getFiredEventsQueue(HttpSession session) {

    synchronized (session) {
        @SuppressWarnings("unchecked")
        TransientObjectWrapper<LinkedMap> eventWrapper = (TransientObjectWrapper<LinkedMap>) session
                .getAttribute(WGACore.SESSION_FIREDPORTLETEVENTS);
        if (eventWrapper == null || eventWrapper.get() == null) {
            eventWrapper = new TransientObjectWrapper<LinkedMap>();
            eventWrapper.set(new LinkedMap());
            session.setAttribute(WGACore.SESSION_FIREDPORTLETEVENTS, eventWrapper);
        }
        return eventWrapper.get();
    }

}

From source file:org.apache.felix.http.itest.SessionHandlingTest.java

private void setupServlet(final String name, String[] path, int rank, final String context) throws Exception {
    Dictionary<String, Object> servletProps = new Hashtable<String, Object>();
    servletProps.put(HTTP_WHITEBOARD_SERVLET_NAME, name);
    servletProps.put(HTTP_WHITEBOARD_SERVLET_PATTERN, path);
    servletProps.put(SERVICE_RANKING, rank);
    if (context != null) {
        servletProps.put(HTTP_WHITEBOARD_CONTEXT_SELECT,
                "(" + HTTP_WHITEBOARD_CONTEXT_NAME + "=" + context + ")");
    }// ww w.  j  a v  a2s . c  om

    Servlet sessionServlet = new TestServlet(initLatch, destroyLatch) {
        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
            final boolean create = req.getParameter("create") != null;
            if (create) {
                req.getSession();
            }
            final boolean destroy = req.getParameter("destroy") != null;
            if (destroy) {
                req.getSession().invalidate();
            }
            final HttpSession s = req.getSession(false);
            if (s != null) {
                s.setAttribute("value", context);
            }

            final PrintWriter pw = resp.getWriter();
            pw.println("{");
            if (s == null) {
                pw.println(" \"session\" : false");
            } else {
                pw.println(" \"session\" : true,");
                pw.println(" \"sessionId\" : \"" + s.getId() + "\",");
                pw.println(" \"value\" : \"" + s.getAttribute("value") + "\"");
            }
            pw.println("}");
        }
    };

    registrations.add(m_context.registerService(Servlet.class.getName(), sessionServlet, servletProps));
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

private void storeTarget(String target, HttpSession httpSession) {
    httpSession.setAttribute(TARGET_SESSION_ATTRIBUTE, target);
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

private void storeSignatureRequest(String signatureRequest, HttpSession httpSession) {
    httpSession.setAttribute(SIGNATURE_REQUEST_SESSION_ATTRIBUTE, signatureRequest);
}

From source file:be.fedict.eid.dss.protocol.simple.SimpleDSSProtocolService.java

private void storeSignatureRequestId(String signatureRequestId, HttpSession httpSession) {
    httpSession.setAttribute(SIGNATURE_REQUEST_ID_SESSION_ATTRIBUTE, signatureRequestId);
}