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.iwethey.forums.web.user.LoginController.java

/**
 * Process a submitted form by placing the user name in the session.
 * <p>//from ww  w  .  j a  va 2s  . co m
 * @param request The servlet request object.
 * @param response The servlet response object.
 * @param command The form backing store object (a User object).
 * @param errors The Spring errors object.
 * @return The model and view.
 */
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command,
        BindException errors) throws Exception {
    User user = (User) command;

    User realUser = mUserManager.getUserByNickname(user.getNickname());

    HttpSession sess = request.getSession();
    sess.setAttribute(USER_ID_ATTRIBUTE, new Integer(realUser.getId()));

    int def = realUser.getDefaultBoard();

    if (def == 0) {
        return new ModelAndView(new RedirectView(getSuccessView()));
    } else {
        return new ModelAndView(new RedirectView("../board/show.iwt?boardid=" + def));
    }
}

From source file:com.hyeb.front.controller.CommonController.java

/**
 * /*from   ww  w.j  a  v a 2 s . c o m*/
 */
@RequestMapping(value = "/public_key", method = RequestMethod.GET)
public @ResponseBody Map<String, String> publicKey(HttpServletRequest request) {
    Assert.notNull(request);
    KeyPair keyPair = RSAUtils.generateKeyPair();
    RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
    RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
    HttpSession session = request.getSession();
    session.setAttribute(PRIVATE_KEY_ATTRIBUTE_NAME, privateKey);

    Map<String, String> data = new HashMap<String, String>();
    data.put("modulus", Base64.encodeBase64String(publicKey.getModulus().toByteArray()));
    data.put("exponent", Base64.encodeBase64String(publicKey.getPublicExponent().toByteArray()));
    return data;
}

From source file:org.apache.niolex.config.ctrl.LoginController.java

@RequestMapping(method = RequestMethod.POST)
public @ResponseBody Map<String, ? extends Object> create(@ModelAttribute LoginInfo info,
        HttpServletRequest req) {/* ww  w.j a  va 2s  . c o  m*/
    Set<ConstraintViolation<LoginInfo>> failures = validator.validate(info);
    if (!failures.isEmpty()) {
        return Collections.singletonMap("msg", failures.iterator().next().getMessage());
    } else {
        CenterConnector updater = null;
        try {
            updater = new CenterConnector(serverAddress);
            String res = updater.subscribeAuthInfo(info.getUsername(), info.getPassword());
            if (!res.startsWith("SUCC")) {
                updater.stop();
                return Collections.singletonMap("msg", "???");
            } else {
                // Attach the updater to session.
                HttpSession sess = req.getSession();
                sess.setAttribute("login_cli", updater);
                // Auth success.
                return Collections.singletonMap("msg", "SUCCESS");
            }
        } catch (Exception e) {
            LOG.error("Error occured when connect to config center.", e);
            if (updater != null) {
                updater.stop();
            }
            return Collections.singletonMap("msg", "?");
        }
    }
}

From source file:edu.slu.tpen.servlet.LoginServlet.java

/**
 * Handles the HTTP <code>POST</code> method by logging in using the given credentials.  Credentials
 * should be specified as a JSON object in the request body.  There is also a deprecated way of passing
 * the credentials as query parameters./*from w w  w . j a  va 2 s  .  com*/
 *
 * @param req servlet request
 * @param resp servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        String mail = null, password = null;
        if (req.getContentLength() > 0) {
            String contentType = getBaseContentType(req);
            if (contentType.equals("application/json")) {
                ObjectMapper mapper = new ObjectMapper();
                Map<String, String> creds = mapper.readValue(req.getInputStream(),
                        new TypeReference<Map<String, String>>() {
                        });
                mail = creds.get("mail");
                password = creds.get("password");
            }
        } else {
            // Deprecated approach where user-name and password are passed on the query string.
            mail = req.getParameter("uname");
            password = req.getParameter("password");
        }
        if (mail != null && password != null) {
            User u = new User(mail, password);
            if (u.getUID() > 0) {
                HttpSession sess = req.getSession(true);
                sess.setAttribute("UID", u.getUID());
            } else {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
            }
        } else if (mail == null && password == null) {
            // Passing null data indicates a logout.
            HttpSession sess = req.getSession(true);
            sess.removeAttribute("UID");
            resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
        } else {
            // Only supplied one of user-id and password.
            resp.sendError(HttpServletResponse.SC_UNAUTHORIZED);
        }
    } catch (NoSuchAlgorithmException ex) {
        reportInternalError(resp, ex);
    }
}

From source file:com.zuoxiaolong.blog.common.web.AbstractController.java

/**
 * ? HttpSession //from  ww  w.j a v a  2 s .c om
 * @param name ??
 * @param value 
 */
public void setSessionAttribute(String name, Object value) {
    HttpSession session = this.getSession();
    session.setAttribute(name, value);
}

From source file:JndiFilter.java

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

    javax.mail.Session mailSession = null;

    try {//from   w  w  w  . j ava  2s. co  m

        mailSession = (javax.mail.Session) env.lookup("MyEmail");

    } catch (NamingException ne) {
    }

    HttpServletRequest hRequest = null;

    if (request instanceof HttpServletRequest) {

        hRequest = (HttpServletRequest) request;

        HttpSession hSession = hRequest.getSession();

        if (hSession != null)
            hSession.setAttribute("MyEmail", mailSession);

    } //if

    chain.doFilter(request, response);

}

From source file:AutoServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {

    //client browser will request the page every 60 seconds
    HttpSession session = request.getSession();
    Long times = (Long) session.getAttribute("times");
    if (times == null)
        session.setAttribute("times", new Long(0));
    long temp = 1;
    if (times != null)
        temp = (times.longValue()) + 1;/*w w w  .j a  va2s . c  om*/

    if (temp < 5)
        response.addHeader("Refresh", "15");

    response.setContentType("text/html");
    java.io.PrintWriter out = response.getWriter();
    out.println("<html><head><title>Client Refresh</title></head><body>");

    //More HTML or dynamic content
    out.println("You've viewed this page " + temp + " times.");
    session.setAttribute("times", new Long(temp));
    out.println("</body></html>");

}

From source file:cs425.yogastudio.controller.SignupController.java

@RequestMapping(value = "/addFaculty", method = RequestMethod.POST)
public String addFaculty(String firstname, String lastname, String gender, String email, String username,
        String password, String state, String zip, String street, String city, Model model,
        HttpSession session) {

    if (checkUsername(username)) {

        session.setAttribute("nonUniqueMessage", null);

        Faculty newFaculty = new Faculty(firstname, lastname, gender, email, username, password);
        Address newAddress = new Address(state, zip, street, city);

        newFaculty.addAddress(newAddress);
        facultyService.add(newFaculty);/*  w  w  w . j  av a 2 s .c  om*/
        //model.addAttribute("newFaculty", newFaculty);
        session.setAttribute("added", newFaculty.getFirstName());
        return "redirect:/signUpSuccess";
    } else {
        String msg = "username already exists, try another one";
        session.setAttribute("nonUniqueMessage", msg);
        return "redirect:/customerSignup";
    }

}

From source file:org.openmrs.module.errorlogging.web.controller.ManageErrorLoggingController.java

@RequestMapping(value = "module/errorlogging/manage.form", method = RequestMethod.POST)
public ModelAndView processSubmit(@RequestParam(value = "exceptions", required = true) String ignoredExceprions,
        ModelMap model, HttpServletRequest request) {
    boolean successSave = saveIgnoredExceprions(ignoredExceprions);
    HttpSession httpSession = request.getSession();
    if (successSave) {
        httpSession.setAttribute(WebConstants.OPENMRS_MSG_ATTR,
                "errorlogging.ignredExceptions.successSaveMessage");
    } else {/*from  w  w  w.jav  a  2 s .  c o  m*/
        httpSession.setAttribute(WebConstants.OPENMRS_ERROR_ATTR,
                "errorlogging.ignredExceptions.errorSaveMessage");
    }
    return new ModelAndView("redirect:./manage.form");
}

From source file:com.impetus.kundera.datakeeper.beans.LoginBean.java

public String authenticate() {
    String outcome = null;//from  www. ja v a 2 s  .c  o m

    // Validates Parameters
    if (StringUtils.isBlank(employee.getEmployeeName())) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter your user name"));
        outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
    }

    if (StringUtils.isBlank(employee.getPassword())) {
        FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("Please enter password"));
        outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
    }

    if (StringUtils.isNotBlank(outcome)) {
        return outcome;
    } else {
        DataKeeperService service = DataKeeperUtils.getService();
        Employee foundEmployee = service.findEmployeeByName(employee.getEmployeeName());
        boolean success = service.authenticateEmployee(foundEmployee, employee.getPassword());

        if (!success) {
            FacesContext.getCurrentInstance().addMessage(null,
                    new FacesMessage("Incorrect User Name/Password"));
            outcome = DataKeeperConstants.OUTCOME_LOGIN_FAILED;
        } else {
            outcome = DataKeeperConstants.OUTCOME_LOGIN_SUCCESSFUL;
            HttpSession session = FacesUtils.getSession();
            session.setAttribute(DataKeeperConstants.EMPLOYEE, foundEmployee);
        }
        return outcome;
    }
}