Example usage for javax.servlet.http HttpServletResponse sendRedirect

List of usage examples for javax.servlet.http HttpServletResponse sendRedirect

Introduction

In this page you can find the example usage for javax.servlet.http HttpServletResponse sendRedirect.

Prototype

public void sendRedirect(String location) throws IOException;

Source Link

Document

Sends a temporary redirect response to the client using the specified redirect location URL and clears the buffer.

Usage

From source file:pivotal.au.se.gemfirexdweb.controller.CreateSchemaController.java

@RequestMapping(value = "/createschema", method = RequestMethod.POST)
public String createSchemaAction(@ModelAttribute("schemaAttribute") NewSchema schemaAttribute, Model model,
        HttpServletResponse response, HttpServletRequest request, HttpSession session) throws Exception {
    if (session.getAttribute("user_key") == null) {
        logger.debug("user_key is null new Login required");
        response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
        return null;
    } else {/*from  w w  w . j a  v a  2 s.c  o  m*/
        Connection conn = AdminUtil.getConnection((String) session.getAttribute("user_key"));
        if (conn == null) {
            response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
            return null;
        } else {
            if (conn.isClosed()) {
                response.sendRedirect(request.getContextPath() + "/GemFireXD-Web/login");
                return null;
            }
        }

    }

    logger.debug("Received request to action an event for create Schema");

    model.addAttribute("schemas", GemFireXDWebDAOUtil.getAllSchemas((String) session.getAttribute("user_key")));

    String schema = schemaAttribute.getSchemaName();

    logger.debug("New Schema name = " + schema);

    // perform some action here with what we have
    String submit = request.getParameter("pSubmit");

    if (submit != null) {
        // build create HDFS Store SQL
        StringBuffer createSchema = new StringBuffer();

        createSchema.append("CREATE SCHEMA ");

        if (!checkIfParameterEmpty(request, "authorizationSchema")) {
            createSchema.append("AUTHORIZATION " + schemaAttribute.getAuthorizationSchema() + " \n");
        } else {
            createSchema.append(schema + " \n");
        }

        if (!checkIfParameterEmpty(request, "serverGroups")) {
            createSchema.append("DEFAULT SERVER GROUPS (" + schemaAttribute.getServerGroups() + ") \n");
        }

        if (submit.equalsIgnoreCase("create")) {
            Result result = new Result();

            logger.debug("Creating Schema as -> " + createSchema.toString());

            result = GemFireXDWebDAOUtil.runCommand(createSchema.toString(),
                    (String) session.getAttribute("user_key"));

            model.addAttribute("result", result);
            model.addAttribute("chosenSchema", schemaAttribute.getAuthorizationSchema());

        } else if (submit.equalsIgnoreCase("Show SQL")) {
            logger.debug("Create Schema SQL as follows as -> " + createSchema.toString());
            model.addAttribute("sql", createSchema.toString());
            model.addAttribute("chosenSchema", schemaAttribute.getAuthorizationSchema());
        } else if (submit.equalsIgnoreCase("Save to File")) {
            response.setContentType(SAVE_CONTENT_TYPE);
            response.setHeader("Content-Disposition",
                    "attachment; filename=" + String.format(FILENAME, schemaAttribute.getSchemaName()));

            ServletOutputStream out = response.getOutputStream();
            out.println(createSchema.toString());
            out.close();
            return null;
        }

    }

    // This will resolve to /WEB-INF/jsp/create-schema.jsp
    return "create-schema";
}

From source file:com.twocharts.www.samples.apps.marketplace.OpenIdServlet.java

/**
 * Handle the response from the OpenID Provider.
 *
 * @param req Current servlet request/*ww  w.  jav  a2 s. co  m*/
 * @param resp Current servlet response
 * @throws ServletException if unable to process request
 * @throws IOException if unable to process request
 */
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {
        UserInfo user = completeAuthentication(req);
        req.getSession().setAttribute("user", user);
        resp.sendRedirect(homePath);
    } catch (OpenIDException e) {
        resp.sendRedirect("?errorString=Error processing OpenID response: " + e.getMessage());
    }
}

From source file:com.qatickets.web.service.AuthFilter.java

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

    HttpServletRequest req = (HttpServletRequest) request;
    HttpServletResponse resp = (HttpServletResponse) response;

    log.debug("In AuthFilter: " + req.getRequestURI());

    UserProfile user = UserHelper.getUser(req);

    if (user == null) {
        // redirect to login page
        String loginUrl = Urls.LOGIN_VIEW + ".html";
        log.debug("Force user login: " + loginUrl);
        resp.sendRedirect(loginUrl);
        return;//from w w w  .  j a v a 2s.  c o m
    }

    loadUserObjects(req);

    chain.doFilter(request, response);

}

From source file:com.envisioncn.it.super_sonic.showcase.support.LoginInterceptor.java

@Override
public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
    String uri = req.getRequestURI();
    if (!uri.startsWith("/resources/") && !uri.startsWith("/icon/") && !uri.startsWith("/pre_login")
            && !uri.startsWith("/login")) {
        HttpSession session = req.getSession();
        String user = SessionUtil.getUser(session);
        if (StringUtils.isEmpty(user)) {
            res.sendRedirect("/pre_login");
            return false;
        }/* w  ww. j  a v  a2 s  . c  o  m*/
    }
    return true;

}

From source file:nl.npcf.eav.web.EAVController.java

@RequestMapping(value = "/edit/**")
public ModelAndView edit(@RequestParam(value = DELETE_PARAMETER, required = false) String deleteParameter,
        HttpServletRequest request, HttpServletResponse response) throws IOException, EAVException {
    if (!eavStore.initialize()) {
        response.sendRedirect(request.getContextPath() + "/service/meta");
        return null;
    }//from  w ww  . j  a va 2  s  . co m
    String baseUrl = request.getContextPath() + "/service/edit";
    EAVStore.Entity entity = null;
    EAVStore.Path path = null;
    String error = null;
    try {
        String key = getFirstPathNode("/edit", request);
        path = getPath("/edit", true, request);
        if (key.isEmpty()) {
            entity = eavStore.createTransientEntity(null);
        } else {
            boolean delete = Boolean.parseBoolean(deleteParameter);
            Map<EAVStore.Path, String> values = getValues(request);
            try {
                entity = eavStore.findByKey(key);
                if (delete) {
                    if (path.isEmpty()) {
                        eavStore.remove(entity);
                        response.sendRedirect(baseUrl);
                    } else {
                        entity = eavStore.remove(entity, path);
                        response.sendRedirect(baseUrl + EAVStore.PATH_SEPARATOR + key + EAVStore.PATH_SEPARATOR
                                + path.getParent());
                    }
                } else {
                    entity = eavStore.setValues(key, values, getPrincipal());
                }
            } catch (NoResultException e) {
                if (delete) {
                    throw e;
                }
                entity = eavStore.createTransientEntity(key);
                for (Map.Entry<EAVStore.Path, String> entry : values.entrySet()) {
                    entity.setTransientValue(entry.getKey(), entry.getValue(), getPrincipal());
                }
                eavStore.persist(entity);
            }
        }
    } catch (EAVValidationException e) {
        if (e.getValue() == null) {
            error = "Validation problem setting " + e.getAttribute().getPrompt() + ": \"" + e.getMessage()
                    + "\".";
        } else {
            error = "Validation problem setting " + e.getAttribute().getPrompt() + "=[" + e.getValue() + "]: \""
                    + e.getMessage() + "\".";
        }
    } catch (EAVPathException e) {
        error = "Path problem using [" + e.getPathString() + "]: \"" + e.getMessage() + "\".";
    } catch (Throwable t) {
        logger.error("Unhandled exception", t);
        error = "Internal problem. It has been logged.";
    }
    ModelAndView modelAndView = new ModelAndView("edit");
    modelAndView.addObject("entity", entity);
    modelAndView.addObject("path", path);
    modelAndView.addObject("baseUrl", baseUrl);
    modelAndView.addObject("error", error);
    return modelAndView;
}

From source file:org.shareok.data.webserv.UserSessionInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    try {// w  w w . j a  v  a2s.  co m
        String contextPath = request.getServletPath();
        if (contextPath.contains("/")) {
            contextPath = contextPath.split("/")[1];
        }
        if (null != contextPath && !"".equals(contextPath)
                && ShareokdataManager.requiredUserAuthentication(contextPath)) {
            SessionRepository<Session> repo = (SessionRepository<Session>) request
                    .getAttribute(SessionRepository.class.getName());

            if (contextPath.equals("register")) {
                if (!configService.getRegistrationConfig()) {
                    throw new NoNewUserRegistrationException("The registraion of new users has been closed!");
                }
                String email = (String) request.getParameter("email");
                String password = pwAuthenService.hash((String) request.getParameter("password"));
                String userName = (String) request.getParameter("nickname");
                if (null == email || "".equals(email)) {
                    throw new UserRegisterInfoNotFoundException(
                            "Valid email register information is required!");
                }
                if (null == password || "".equals(password)) {
                    throw new UserRegisterInfoNotFoundException("Valid password is required for registration!");
                }
                /*****************
                 * Some password validation logic here:
                 */
                HttpSession httpSession = (HttpSession) request.getSession();
                ExpiringSession session = (ExpiringSession) repo.getSession(httpSession.getId());
                if (null == session) {
                    session = (ExpiringSession) repo.createSession();
                }
                String sessionId = session.getId();
                RedisUser user = redisUserService.findUserByUserEmail(email);
                if (null != user) {
                    throw new RegisterUserInfoExistedException("User Email has already Existed!");
                } else {
                    user = redisUserService.getNewUser();
                    user.setEmail(email);
                    user.setPassword(password);
                    if (null == userName || userName.equals("")) {
                        userName = email;
                    }
                    user.setUserName(userName);
                    user.setSessionKey(sessionId);
                    redisUserService.addUser(user);
                }

                setSessionUserInfo(session, httpSession, user);
                repo.save(session);
            } else if (contextPath.equals("userLogin")) {
                String email = (String) request.getParameter("email");
                String password = (String) request.getParameter("password");
                if (null == email || "".equals(email)) {
                    throw new UserRegisterInfoNotFoundException(
                            "Valid email information is required for logging in!");
                }
                if (null == password || "".equals(password)) {
                    throw new UserRegisterInfoNotFoundException("Valid password is required for logging in!");
                }
                /*****************
                 * Some password validation logic here:
                 */
                HttpSession httpSession = (HttpSession) request.getSession();
                ExpiringSession session = (ExpiringSession) repo.getSession(httpSession.getId());
                if (null == session || session.isExpired()) {
                    session = (ExpiringSession) repo.createSession();
                }
                String sessionId = session.getId();
                RedisUser user = redisUserService.findUserByUserEmail(email);

                if (null == user || !pwAuthenService.authenticate(password, user.getPassword())) {
                    throw new UserRegisterInfoNotFoundException("User information cannot be found!");
                }

                user.setSessionKey(sessionId);
                redisUserService.updateUser(user);

                setSessionUserInfo(session, httpSession, user);
                httpSession.setAttribute("email", email);
                repo.save(session);
            } else if (contextPath.equals("logout")) {
                HttpSession session = (HttpSession) request.getSession(false);
                if (null != session) {
                    ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId());
                    if (null != exSession) {
                        String email = (String) session.getAttribute("email");
                        if (null != email) {
                            redisUserService.invalidateUserSessionIdByEmail(email);
                        }
                        exSession.isExpired();
                        repo.delete(exSession.getId());
                    }
                    session.invalidate();
                }
            }
            // *** The following situation applies to authentication logic based on session information ***
            else {
                boolean sessionValidated = false;
                HttpSession session = (HttpSession) request.getSession(false);
                if (null != session) {
                    ExpiringSession exSession = (ExpiringSession) repo.getSession(session.getId());
                    if (null != exSession && !exSession.isExpired()) {
                        String email = (String) session.getAttribute("email");
                        if (null != email) {
                            RedisUser userPersisted = redisUserService.findAuthenticatedUser(email,
                                    session.getId());
                            if (null != userPersisted) {
                                sessionValidated = true;
                            }
                        }
                    }
                }

                if (!sessionValidated) {
                    if (null != session) {
                        repo.delete(session.getId());
                        session.setAttribute(ShareokdataManager.getSessionRedisUserAttributeName(), null);
                        session.invalidate();
                    }
                    request.logout();
                    //request.getRequestDispatcher("/WEB-INF/jsp/logout.jsp").forward(request, response);
                    HttpServletResponse httpReponse = (HttpServletResponse) response;
                    httpReponse.sendRedirect("/webserv/login");
                }
            }
        } else {
            ;
        }
    } catch (IOException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (ServletException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (UserRegisterInfoNotFoundException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (RegisterUserInfoExistedException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/userError.jsp").forward(request, response);
    } catch (NoNewUserRegistrationException ex) {
        request.setAttribute("errorMessage", ex.getMessage());
        request.getRequestDispatcher("/WEB-INF/jsp/closedRegistration.jsp").forward(request, response);
    }

    return true;
}

From source file:com.app.controller.interceptor.AuthenticationInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {

    Subject currentUser = SecurityUtils.getSubject();

    if (!currentUser.isAuthenticated()) {
        String originalUrl = (String) request
                .getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE);

        WebUtils.setSessionAttribute(request, "redirect", originalUrl);

        response.sendRedirect("log_in");

        return false;
    }/*from w w  w  .  j av a2 s . c om*/

    return true;
}

From source file:controller.servlet.PostServlet.java

private void addTopic(HttpServletRequest request, HttpServletResponse response, Post post)
        throws ServletException, IOException {
    PostDAOService postService = PostDAO.getInstance();
    if (postService.insertPost(post)) {
        response.sendRedirect("attach?action=load&id=" + post.getPostID());
    } else {//from  www. jav a2s .  com
        request.setAttribute(Constants.CURRENT_POST, post);
        request.setAttribute(Constants.MSG_RESULT, "Li");
        request.setAttribute(Constants.PAGE, "new-topic");
        request.getRequestDispatcher(Constants.URL_HOME).forward(request, response);
    }
}

From source file:nl.npcf.eav.web.EAVController.java

@RequestMapping("/find/**")
public ModelAndView find(HttpServletRequest request, HttpServletResponse response)
        throws EAVException, IOException {
    if (!eavStore.initialize()) {
        response.sendRedirect(request.getContextPath() + "/service/meta");
        return null;
    }//from ww w  .jav a  2s.  c  o m
    EAVStore.Path path = null;
    String error = null;
    List<EAVStore.Value> valueList = null;
    EAVStore.Attribute attribute = null;
    try {
        path = getPath("/find", false, request);
        attribute = eavStore.getSchema().getAttribute(path, false);
        if (!attribute.isAggregate()) {
            Map<EAVStore.Path, String> values = getValues(request);
            switch (values.size()) {
            case 0:
                break;
            case 1:
                Map.Entry<EAVStore.Path, String> entry = values.entrySet().iterator().next();
                if (entry.getValue().isEmpty()) {
                    valueList = eavStore.findByAttribute(attribute);
                } else {
                    Object value = attribute.stringToValue(entry.getValue());
                    valueList = eavStore.findByValue(attribute, value);
                }
                break;
            default:
                break;
            }
        }
    } catch (EAVValidationException e) {
        if (e.getValue() == null) {
            error = "Validation problem setting " + e.getAttribute().getPrompt() + ": \"" + e.getMessage()
                    + "\".";
        } else {
            error = "Validation problem setting " + e.getAttribute().getPrompt() + "=[" + e.getValue() + "]: \""
                    + e.getMessage() + "\".";
        }
    } catch (EAVPathException e) {
        error = "Path problem using [" + e.getPathString() + "]: \"" + e.getMessage() + "\".";
    } catch (Throwable t) {
        logger.error("Unhandled exception", t);
        error = "Internal problem. It has been logged.";
    }
    ModelAndView modelAndView = new ModelAndView("find");
    modelAndView.addObject("schema", eavStore.getSchema());
    modelAndView.addObject("path", path);
    modelAndView.addObject("attribute", attribute);
    modelAndView.addObject("valueList", valueList);
    modelAndView.addObject("baseUrl", request.getContextPath() + "/service/find");
    modelAndView.addObject("baseEditUrl", request.getContextPath() + "/service/edit");
    modelAndView.addObject("error", error);
    return modelAndView;
}

From source file:org.chos.transaction.passport.controller.TencentPassportController.java

@RequestMapping(value = "/qq/login")
public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String code = request.getParameter("code");
    String state = request.getParameter("state");
    OAuthSession session = sessionService.getSession(state);
    if (session == null) {
        response.sendRedirect("http://chos2009.eicp.net/login.shtml");
    }/*from  w ww  .j av a  2  s. com*/
    if (state == null) {
        response.sendRedirect("http://chos2009.eicp.net/login.shtml");
    }
    if (!state.equals(session.getState())) {
        response.sendRedirect("http://chos2009.eicp.net/login.shtml");
    }
    Map<String, String> param = new HashMap<String, String>();
    param.put("client_id", "101207948");
    param.put("client_secret", "9ecb9b104ff172c2d0724840bd118e81");
    param.put("grant_type", "authorization_code");
    param.put("code", code);
    param.put("redirect_uri", "http://chos2009.eicp.net");
    HttpTemplate template = new HttpTemplate();
    String resp = null;
    try {
        resp = template.post("https://graph.qq.com/oauth2.0/token", param);
    } catch (HttpException e) {
        response.sendRedirect("http://chos2009.eicp.net/login.shtml");
    }
    Map<String, Object> paramMap = parseParam(resp);
    String ak = (String) paramMap.get("access_token");

    param = new HashMap<String, String>();
    param.put("access_token", ak);
    try {
        resp = template.post("https://graph.qq.com/oauth2.0/me", param);
    } catch (HttpException e) {
        response.sendRedirect("http://chos2009.eicp.net/login.shtml");
    }
    //callback( {"client_id":"101207948","openid":"1901C7D0BCBE69A661738BF19F9660F8"} );
    int indexs = resp.indexOf("{");
    int indexe = resp.indexOf("}");
    resp = resp.substring(indexs, indexe + 1);
    JSONObject json = JSONObject.fromObject(resp);
    String openId = json.getString("openid");

    param = new HashMap<String, String>();
    param.put("access_token", ak);
    param.put("oauth_consumer_key", "101207948");
    param.put("openid", openId);
    try {
        resp = template.post("https://graph.qq.com/user/get_user_info", param);
    } catch (HttpException e) {
        response.sendRedirect("http://chos2009.eicp.net/login.shtml");
    }
    json = JSONObject.fromObject(resp);
    String nickname = json.getString("nickname");

    User user = userService.create(openId + "@qq", null, "13120984792", "13120984792@qq.com", true, request,
            response);
    response.sendRedirect("http://chos2009.eicp.net/mindex.htm");
}