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:wqm.web.server.controller.BaseWQMController.java

protected Station validateStation(HttpSession session, String stationAddress) {
    Station station = config.getStation(stationAddress);
    if (station == null) {
        session.setAttribute(Messages.ERROR_MESSAGE, "Invalid station.");
        throw new RedirectException(".");
    }/*w w w .j  av a 2 s  . co  m*/
    return station;
}

From source file:com.glaf.core.util.RequestUtils.java

public static void setLoginUser(HttpServletRequest request, HttpServletResponse response, String systemName,
        String actorId) {//from w  w  w  .  j av  a2s  . co m
    String ip = getIPAddress(request);
    ip = DigestUtils.md5Hex(ip);
    String value = encodeValues(ip, systemName, actorId);
    HttpSession session = request.getSession(false);
    if (session != null) {
        session.setAttribute(Constants.LOGIN_INFO, value);
    }
    Cookie cookie = new Cookie(Constants.COOKIE_NAME, value);
    cookie.setPath("/");
    cookie.setMaxAge(-1);
    response.addCookie(cookie);
}

From source file:com.aurel.track.prop.LoginBL.java

/**
 * This method controls entire login procedure.
 *
 * @param isInTestMode// w w  w.  j  av  a  2 s  . co m
 * @param isMobileApplication
 * @param username
 * @param usingContainerBasedAuthentication
 * @param password
 * @param forwardUrl
 * @param springAuthenticated
 * @param mobileApplicationVersionNo
 * @param locale
 * @return
 */
public static String login(String isInTestMode, boolean isMobileApplication, String username,
        boolean usingContainerBasedAuthentication, String password, String forwardUrl,
        boolean springAuthenticated, Integer mobileApplicationVersionNo, Locale _locale) {
    Boolean ready = (Boolean) ServletActionContext.getServletContext().getAttribute(ApplicationStarter.READY);
    if (ready == null || !ready.booleanValue()) {
        return "loading";
    }
    HttpServletRequest request = ServletActionContext.getRequest();
    HttpSession httpSession = request.getSession();
    String nonce = (String) httpSession.getAttribute("NONCE");

    if ("true".equals(isInTestMode)) {
        nonce = null; // accept clear text passwords
    }

    httpSession.setAttribute(ISMOBILEAPP, isMobileApplication);

    Locale locale = _locale;
    if (locale == null) {
        locale = Locale.getDefault();
        LOGGER.debug("Requested locale is null. Using default:" + locale.getDisplayName());
    } else {
        LOGGER.debug("Requested locale " + locale.getDisplayName());
    }
    httpSession.setAttribute("localizationJSON", LocalizeJSON.encodeLocalization(locale));
    TMotdBean motd = MotdBL.loadMotd(locale.getLanguage());

    if (motd == null) {
        motd = MotdBL.loadMotd("en");
    }
    // if already logged in forward to home page
    if (SessionUtils.getCurrentUser(httpSession) != null) {

        String redirectMapEntry = "itemNavigator";
        TPersonBean personBean = (TPersonBean) httpSession.getAttribute(Constants.USER_KEY);
        if (personBean != null && personBean.getHomePage() != null
                && personBean.getHomePage().trim().length() > 0) {
            redirectMapEntry = personBean.getHomePage();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        JSONUtility.appendBooleanValue(sb, JSONUtility.JSON_FIELDS.SUCCESS, true);
        sb.append(DATABRACE);
        JSONUtility.appendStringValue(sb, "jsonURL", redirectMapEntry + DOTACTION, true);
        sb.append("}");
        sb.append("}");
        return LoginBL.writeJSONResponse(sb); // The redirect is done by the
        // client JavaScript
    }
    // if Container Based Authentication is enabled and we can get a remote
    // user we use that one, no more questions asked. However, a local login
    // always overrules.

    if ((username == null || "".equals(username) || password == null || "".equals(password))
            && (request.getRemoteUser() != null
                    && ApplicationBean.getInstance().getSiteBean().getIsCbaAllowed())) {
        username = request.getRemoteUser();
        usingContainerBasedAuthentication = true;
    }

    List<LabelValueBean> errors = new ArrayList<LabelValueBean>();
    StringBuilder sb = new StringBuilder();
    String redirectMapEntry = "";
    sb = LoginBL.createLoginResponseJSON(username, password, nonce, usingContainerBasedAuthentication,
            springAuthenticated, request, errors, httpSession, forwardUrl, motd, isMobileApplication, locale,
            mobileApplicationVersionNo, redirectMapEntry);

    if (errors != null && errors.size() > 0 && usingContainerBasedAuthentication) {
        return "forwardToLogin"; // could not verify container registered
        // user with Genji
    }

    if (usingContainerBasedAuthentication && !isMobileApplication) {
        ACCESSLOGGER.info("User was authenticated via container.");
        if (redirectMapEntry.isEmpty())
            return SUCCESS;
        return redirectMapEntry;
    }
    return writeJSONResponse(sb); // The redirect is done by the client
    // JavaScript
}

From source file:duoc.cl.dej4501.DejMobile.Presentacion.RegistrarClienteServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession sesion = request.getSession();
    String rut = request.getParameter("txtRut");
    if (objClienteSessionBeans.validarRut(rut) == false) {
        sesion.setAttribute("rutInvalidoMsg", "Rut ingresado no es valido");
        request.getRequestDispatcher("./RegistroCliente.jsp").forward(request, response);
    }//from   ww w .j ava2  s.c  o  m
    if (objClienteSessionBeans.buscaUsuarioXRut(rut) != null) {
        sesion.setAttribute("rutInvalidoMsg", "Rut ingresado ya se encuentra en el sistema");
        request.getRequestDispatcher("./RegistroCliente.jsp").forward(request, response);

    }
    String clave = DigestUtils.md5Hex(request.getParameter("txtClave"));
    String confirmarClave = DigestUtils.md5Hex(request.getParameter("txtConfirmarClave"));
    if (clave.equals(confirmarClave) == false) {
        sesion.setAttribute("claveInvalidaMsg", "Password invalida");
        response.sendRedirect("RegistroCliente.jsp");
    }
    String nombre = request.getParameter("txtNombre");
    String apellidoPaterno = request.getParameter("txtApellidoPaterno");
    String apellidoMaterno = request.getParameter("txtApellidoMaterno");
    String direccion = request.getParameter("txtDireccion");
    int numeracion = Integer.parseInt(request.getParameter("txtNumeracion"));
    int comuna = Integer.parseInt(request.getParameter("ddlComuna"));
    int telefono = Integer.parseInt(request.getParameter("txtTelefono"));
    ClienteDTO infoClienteDTO = new ClienteDTO(rut, clave, nombre, apellidoPaterno, apellidoMaterno, direccion,
            numeracion, comuna, telefono);
    try {
        objClienteSessionBeans.addCliente(infoClienteDTO);
        sesion.setAttribute("msgCorrecto", "Cliente Ingresado de forma correcta");
        response.sendRedirect("Login.jsp");

    } catch (Exception ex) {
        sesion.setAttribute("msgError", "Cliente no pudo ingresar a la base de datos");
        response.sendRedirect("RegistroCliente.jsp");
    }
}

From source file:com.ggfix.gg.user.controller.UserAuthorityController.java

@RequestMapping("/login")
public String login(String account, String password, HttpSession session) {
    if (this.userManager.login(account, password)) {
        List<User> users = this.userManager.getUsersByEmail(account);
        if (users != null) {
            session.setAttribute("User", users.get(0));
            session.setAttribute("UserId", users.get(0).getId());
            session.setAttribute("UserName", users.get(0).getFirstName());
            session.removeAttribute("errorInfo");
        }//from ww  w.j  av  a  2  s.  co m
    } else {
        if (session.getAttribute("UserName") == null)
            session.setAttribute("UserName", session.getId());
        session.setAttribute("errorInfo", "wrongUserOrPassword");
    }
    return "index";
}

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

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

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

    RegistrationForm registrationForm = new RegistrationForm();
    registrationForm.setName(name);//from ww  w .  j  av  a  2  s  .com
    registrationForm.setEmail(email);
    registrationForm.setPassword(password);
    registrationForm.setConfirmationPassword(confirmationPassword);

    String nextPage = REGISTER_PAGE;

    validateRegistrationForm(request, registrationForm);

    checkPasswordsMatch(request, password, confirmationPassword);

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

    if (isAlreadyUsed(email)) {
        request.setAttribute("error",
                MessageFormat.format(resourceBundle.getString("register.error.global.account"), email));
        request.getRequestDispatcher(nextPage).forward(request, response);
        return;
    }

    User user = new User(name, email, password);
    user = userService.create(user);
    HttpSession session = request.getSession(true);
    session.setAttribute(TodoListUtils.SESSION_USER, user);
    request.getRequestDispatcher("/todos").forward(request, response);

}

From source file:th.co.geniustree.osgi.prototype.authen.impl.AuthenStoreImpl.java

@Override
public void storeAuthentication(HttpSession session, Authentication authentication) {
    if (store != null) {
        validateSessionStore();/*from w ww .  j av  a2 s  . com*/

        HttpSession ssion = store.findSession(session.getId());
        if (ssion == null) {
            ssion = session;
            store.storeSession(ssion.getId(), ssion);
        }

        ssion.setAttribute(AUTHENTICATION_SESSION, authentication);
    }
}

From source file:org.freeeed.search.web.controller.LoginController.java

@Override
public ModelAndView execute() {
    String username = (String) valueStack.get("username");
    String password = (String) valueStack.get("password");

    log.debug("Login attempt for: " + username);

    User user = null;//  w w w.j av a2s. com

    if (username != null && password != null) {
        user = userDao.login(username, password);
        if (user != null) {
            HttpSession session = request.getSession();
            LoggedSiteVisitor loggedSiteVisitor = new LoggedSiteVisitor();
            loggedSiteVisitor.setUser(user);

            session.setAttribute(WebConstants.LOGGED_SITE_VISITOR_SESSION_KEY, loggedSiteVisitor);

            this.loggedSiteVisitor = loggedSiteVisitor;

            log.debug("User: " + username + " logged in! IP address: " + request.getRemoteHost());
        }
    }

    if (user == null) {
        valueStack.put("loginError", true);
    }

    return new ModelAndView(WebConstants.MAIN_PAGE);
}

From source file:com.flexive.shared.FxContext.java

private static void setLastUserTicket(HttpSession session, UserTicket lastUserTicket) {
    session.setAttribute("LAST_USERTICKET", lastUserTicket);
}

From source file:com.silverpeas.servlets.upload.AjaxFileUploadServlet.java

private synchronized void startingToSaveUploadedFile(HttpSession session) {
    session.setAttribute(SAVING_FILE_FLAG, SAVING_FILE_FLAG);
}