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:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.actions.SaveClientLoginAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed./* w w  w .  j  a  va 2s  .  co  m*/
 *
 * @param mapping The ActionMapping used to select this instance
 * @param actionForm The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();

    if ("request".equals(mapping.getScope())) {
        request.setAttribute(mapping.getAttribute(), form);
    } else {
        session.setAttribute(mapping.getAttribute(), form);
    }

    DynaValidatorForm loginForm = (DynaValidatorForm) form;

    String email = (String) loginForm.get("email");
    String password = (String) loginForm.get("password");

    log.info("Logging in client: " + email);
    int clientId = ControlServ.dbw.getClientIdByEmailAndPassword(email, password, JMConstants.USER_ROLE);
    log.info("Client logged in: " + email + " : " + clientId);
    if (clientId < 0) {
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.client.notRegistered"));
        saveErrors(request, errors);
        return (mapping.findForward("failure"));
    }

    loginClient(session, clientId);

    Boolean joiningExp = (Boolean) session.getAttribute("joiningExp");
    if (joiningExp == null || joiningExp == Boolean.FALSE) {
        ActionMessages msg = new ActionMessages();
        msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("client.login.success"));
        saveMessages(request, msg);

        session.removeAttribute("joiningExp");
        return (mapping.findForward("success"));
    } else { //directly join an experiment if the client was sent to login from the EditJoinExpAction
        session.removeAttribute("joiningExp");
        return (mapping.findForward("join"));
    }
}

From source file:org.openmrs.module.referenceapplication.page.controller.UserAppPageController.java

public String post(PageModel model, @ModelAttribute(value = "appId") @BindParams UserApp userApp,
        @RequestParam("action") String action, @SpringBean("appFrameworkService") AppFrameworkService service,
        HttpSession session, UiUtils ui) {

    try {/*  w  ww .ja  v  a  2s  .c o m*/
        AppDescriptor descriptor = mapper.readValue(userApp.getJson(), AppDescriptor.class);
        if (!userApp.getAppId().equals(descriptor.getId())) {
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE,
                    ui.message("referenceapplication.app.errors.IdsShouldMatch"));
        } else if ("add".equals(action) && service.getUserApp(userApp.getAppId()) != null) {
            session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE,
                    ui.message("referenceapplication.app.errors.duplicateAppId"));
        } else {
            service.saveUserApp(userApp);

            InfoErrorMessageUtil.flashInfoMessage(session,
                    ui.message("referenceapplication.app.userApp.save.success", userApp.getAppId()));

            return "redirect:/referenceapplication/manageApps.page";
        }
    } catch (Exception e) {
        session.setAttribute(UiCommonsConstants.SESSION_ATTRIBUTE_ERROR_MESSAGE,
                ui.message("referenceapplication.app.userApp.save.fail", userApp.getAppId()));
    }

    model.addAttribute("userApp", userApp);

    return null;
}

From source file:alfio.controller.AdminConfigurationController.java

@RequestMapping("/admin/configuration/payment/stripe/connect/{orgId}")
public String redirectToStripeConnect(Principal principal, @PathVariable("orgId") Integer orgId,
        HttpSession session) {
    if (userManager.isOwnerOfOrganization(userManager.findUserByUsername(principal.getName()), orgId)) {
        StripeManager.ConnectURL connectURL = stripeManager.getConnectURL(Configuration.from(orgId));
        session.setAttribute(STRIPE_CONNECT_STATE_PREFIX + orgId, connectURL.getState());
        session.setAttribute(STRIPE_CONNECT_ORG, orgId);
        return "redirect:" + connectURL.getAuthorizationURL();
    }//from   w w  w.ja v a  2  s . com
    return "redirect:/admin/";
}

From source file:com.connsec.web.oauth.flow.ClientOAuthAction.java

/**
 * Save a request parameter in the web session.
 *
 * @param request The HTTP request/*  w  w  w  . java2  s  .co m*/
 * @param session The HTTP session
 * @param name The name of the parameter
 */
private void saveRequestParameter(final HttpServletRequest request, final HttpSession session,
        final String name) {
    final String value = request.getParameter(name);
    if (value != null) {
        session.setAttribute(name, value);
    }
}

From source file:nl.surfnet.coin.selfservice.filter.ApiOAuthFilter.java

private void initiateOauthAuthorization(HttpServletRequest httpRequest, HttpServletResponse response,
        HttpSession session) throws IOException {
    final String currentRequestUrl = getCurrentRequestUrl(httpRequest);
    session.setAttribute(ORIGINAL_REQUEST_URL, currentRequestUrl);
    response.sendRedirect(apiClient.getAuthorizationUrl());
}

From source file:edu.caltechUcla.sselCassel.projects.jMarkets.frontdesk.web.actions.SaveClientRegAction.java

/**
 * Process the specified HTTP request, and create the corresponding HTTP
 * response (or forward to another web component that will create it).
 * Return an <code>ActionForward</code> instance describing where and how
 * control should be forwarded, or <code>null</code> if the response has
 * already been completed.// ww w  .  j av  a2  s. c om
 *
 * @param mapping The ActionMapping used to select this instance
 * @param actionForm The optional ActionForm bean for this request (if any)
 * @param request The HTTP request we are processing
 * @param response The HTTP response we are creating
 *
 * @exception Exception if the application business logic throws
 *  an exception
 */
public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    // Extract attributes we will need
    HttpSession session = request.getSession();

    if ("request".equals(mapping.getScope())) {
        request.setAttribute(mapping.getAttribute(), form);
    } else {
        session.setAttribute(mapping.getAttribute(), form);
    }

    DynaValidatorForm regForm = (DynaValidatorForm) form;

    String email = (String) regForm.get("email");
    String fname = (String) regForm.get("fname");
    String lname = (String) regForm.get("lname");
    String phone = (String) regForm.get("phone");
    String password = (String) regForm.get("password");

    String date = new SimpleDateFormat("yyyy-MM-dd").format(Calendar.getInstance().getTime());

    String query = "insert into jm_user values(0,'" + email + "','" + fname + "','" + lname + "','" + phone
            + "',PASSWORD('" + password + "'), 'none', '" + date + "', 0, 0," + JMConstants.USER_ROLE + " )";

    int clientId = ControlServ.dbw.registerSubject(query);

    if (clientId < 0) {
        ActionMessages errors = new ActionMessages();
        errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("error.email.unique", email));
        saveErrors(request, errors);
        return (mapping.findForward("failure"));
    }

    loginClient(session, clientId);

    ActionMessages msg = new ActionMessages();
    msg.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("client.reg.success"));
    saveMessages(request, msg);

    return (mapping.findForward("success"));
}

From source file:SessionSnoop.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("count");
    if (count == null)
        count = new Integer(1);
    else//from   www  . ja  v  a 2  s.c om
        count = new Integer(count.intValue() + 1);
    session.setAttribute("count", count);

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

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

    out.println("<P>");

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

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

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("snoop.count");
    if (count == null)
        count = new Integer(1);
    else/*from www  . j a  v a  2  s .  c  o m*/
        count = new Integer(count.intValue() + 1);
    session.setAttribute("snoop.count", count);

    out.println("<HTML><HEAD><TITLE>SessionSnoop</TITLE></HEAD>");
    out.println("<BODY><H1>Session Snoop</H1>");

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

    out.println("<P>");

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

    out.println("<H3>Here are some vital stats on your session:</H3>");
    out.println("Session id: " + session.getId() + " <I>(keep it secret)</I><BR>");
    out.println("New session: " + session.isNew() + "<BR>");
    out.println("Timeout: " + session.getMaxInactiveInterval());
    out.println("<I>(" + session.getMaxInactiveInterval() / 60 + " minutes)</I><BR>");
    out.println("Creation time: " + session.getCreationTime());
    out.println("<I>(" + new Date(session.getCreationTime()) + ")</I><BR>");
    out.println("Last access time: " + session.getLastAccessedTime());
    out.println("<I>(" + new Date(session.getLastAccessedTime()) + ")</I><BR>");

    out.println("Requested session ID from cookie: " + req.isRequestedSessionIdFromCookie() + "<BR>");
    out.println("Requested session ID from URL: " + req.isRequestedSessionIdFromURL() + "<BR>");
    out.println("Requested session ID valid: " + req.isRequestedSessionIdValid() + "<BR>");

    out.println("<H3>Test URL Rewriting</H3>");
    out.println("Click <A HREF=\"" + res.encodeURL(req.getRequestURI()) + "\">here</A>");
    out.println("to test that session tracking works via URL");
    out.println("rewriting even when cookies aren't supported.");

    out.println("</BODY></HTML>");
}

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

@RequestMapping(value = "/process-login", method = RequestMethod.POST)
public String processLogin(String userName, String password, HttpSession session) {

    //process username and password sent from login form
    Customer customer = customerService.getCustomerByEmail(userName);
    if (customer != null) {

        //if successfull, create session to indicate user already login
        session.setAttribute("userName", userName);
        session.setAttribute("customer", customer);
        //redirect to homepage
        return "redirect:/";
    } else {/*www. ja  v a 2 s.c om*/
        session.setAttribute("errorMessage", "User " + userName + " tidak ditemukan atau password salah");
        return "redirect:/login";
    }

}

From source file:org.eg.sc.web.ShopCartAction.java

public String login() {
    User u = shoppingCartServiceImpl.login(user);
    if (u == null) {
        return ERROR;
    } else {/*from ww  w  .  j  a v a  2 s .  c o m*/
        HttpSession session = ServletActionContext.getRequest().getSession();
        // OrderCar car = (OrderCar) session.getAttribute("Car");
        // OrderCar car = new OrderCar();
        session.setAttribute("User", u);
        // session.setAttribute("Car", car);
        return "list";
    }
}