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:se.inera.certificate.web.security.BrowserClosedInterceptor.java

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

    HttpSession session = request.getSession();
    DateTime then = (DateTime) session.getAttribute(BROWSER_CLOSED_TIMESTAMP);

    if (then != null) {
        if (then.plusSeconds(timeoutSeconds).isBefore(DateTime.now())) {
            LOG.warn("Browser closed and protected page revisited, user logged out");
            // log out user
            logoutHandler.logout(request, response, null);
            response.sendRedirect(redirectLocation);
            return false;
        } else {//  w  w w  .  ja v a  2  s .com
            // valid reqest remove timestamp
            session.removeAttribute(BROWSER_CLOSED_TIMESTAMP);
            LOG.debug("Valid refresh of browser");
            return true;
        }
    }
    // normal request
    return true;
}

From source file:com.qcadoo.mes.technologies.controller.TechnologyMultiUploadController.java

@RequestMapping(value = "/getAttachment.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(TechnologiesConstants.PLUGIN_IDENTIFIER,
            TechnologiesConstants.MODEL_TECHNOLOGY_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService/*  w w  w. j  ava  2s .c  o  m*/
            .getInputStream(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT));

    try {
        if (is == null) {
            response.sendRedirect("/error.html?code=404");
        }

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(TechnologyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(TechnologyAttachmentFields.ATTACHMENT)));

        int bytes = IOUtils.copy(is, response.getOutputStream());
        response.setContentLength(bytes);

        response.flushBuffer();

    } catch (IOException e) {
        logger.error("Unable to copy attachment file to response stream.", e);
    }
}

From source file:com.zb.app.common.ZuobianDispatcherServlet.java

@Override
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
    try {/*from w w  w  . j  a v a  2  s .  co m*/
        CookieManager cookieManager = CookieManagerLocator.get(request, response);
        ZuobianWebUser webUser = ZuobianWebUserBuilder.create(cookieManager);
        if (webUser.hasLogin()) {
            super.noHandlerFound(request, response);
            return;
        }
    } catch (Exception e) {
        logger.debug("url noHandlerFound and parse cookies error!");
    }
    response.sendRedirect("/index.htm");
}

From source file:com.alibaba.sample.petstore.web.common.PetstoreUserAuth.java

public void onDeny(Status status) throws Exception {
    HttpServletRequest request = status.rundata.getRequest();
    HttpServletResponse response = status.rundata.getResponse();
    URIBroker redirectURI = uriBrokerService.getURIBroker(brokerId);

    assertNotNull(redirectURI, "no URI broker found: %s", brokerId);

    StringBuffer buf = request.getRequestURL();
    String queryString = trimToNull(request.getQueryString());

    if (queryString != null) {
        buf.append('?').append(queryString);
    }//from w  w  w.ja  v a  2 s  . com

    String returnURL = buf.toString();

    response.sendRedirect(redirectURI.addQueryData(returnKey, returnURL).render());
}

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

@RequestMapping(value = "/procs", method = RequestMethod.POST)
public String performProcAction(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  www  .ja va2s .  co 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;
            }
        }

    }

    int startAtIndex = 0, endAtIndex = 0;
    String schema = null;
    Result result = new Result();
    List<StoredProc> procs = null;

    logger.debug("Received request to perform an action on the procs");
    String procType = request.getParameter("procType");
    logger.debug("procType = " + procType);

    String selectedSchema = request.getParameter("selectedSchema");
    logger.debug("selectedSchema = " + selectedSchema);

    if (selectedSchema != null) {
        schema = selectedSchema;
    } else {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("schema = " + schema);

    StoredProcDAO procDAO = GemFireXDWebDAOFactory.getStoredProcDAO();

    if (request.getParameter("search") != null) {
        procs = procDAO.retrieveProcList(schema, (String) request.getParameter("search"),
                (String) request.getParameter("procType"), (String) session.getAttribute("user_key"));

        model.addAttribute("search", (String) request.getParameter("search"));
    } else {
        String[] tableList = request.getParameterValues("selected_proc[]");
        String commandStr = request.getParameter("submit_mult");

        logger.debug("tableList = " + Arrays.toString(tableList));
        logger.debug("command = " + commandStr);

        // start actions now if tableList is not null

        if (tableList != null) {
            List al = new ArrayList<Result>();
            for (String procName : tableList) {
                result = null;
                result = procDAO.simpleprocCommand(schema, procName, commandStr,
                        request.getParameter("procType").equals("P") ? "procedure" : "function",
                        (String) session.getAttribute("user_key"));
                al.add(result);
            }

            model.addAttribute("arrayresult", al);
        }

        procs = procDAO.retrieveProcList(schema, null, (String) request.getParameter("procType"),
                (String) session.getAttribute("user_key"));
    }

    model.addAttribute("procType", procType);
    model.addAttribute("records", procs.size());
    model.addAttribute("estimatedrecords", procs.size());

    UserPref userPref = (UserPref) session.getAttribute("prefs");

    if (procs.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("procs", procs);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > procs.size()) {
                endAtIndex = procs.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();
        }

        List subList = procs.subList(startAtIndex, endAtIndex);
        model.addAttribute("procs", subList);
    }

    model.addAttribute("startAtIndex", startAtIndex);
    model.addAttribute("endAtIndex", endAtIndex);

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

    model.addAttribute("chosenSchema", schema);

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

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

@RequestMapping(value = "/types", method = RequestMethod.POST)
public String performTypeAction(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  ww  .  j a  va  2  s . c om
        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;
            }
        }

    }

    int startAtIndex = 0, endAtIndex = 0;
    String schema = null;
    Result result = new Result();
    List<Type> types = null;
    String ddlString = null;

    logger.debug("Received request to perform an action on the types");

    TypeDAO typeDAO = GemFireXDWebDAOFactory.getTypeDAO();

    String selectedSchema = request.getParameter("selectedSchema");
    logger.debug("selectedSchema = " + selectedSchema);

    if (selectedSchema != null) {
        schema = selectedSchema;
    } else {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("schema = " + schema);

    if (request.getParameter("search") != null) {
        types = typeDAO.retrieveTypeList(schema, (String) request.getParameter("search"),
                (String) session.getAttribute("user_key"));

        model.addAttribute("search", (String) request.getParameter("search"));
    } else {
        String[] tableList = request.getParameterValues("selected_type[]");
        String commandStr = request.getParameter("submit_mult");

        logger.debug("tableList = " + Arrays.toString(tableList));
        logger.debug("command = " + commandStr);

        // start actions now if tableList is not null

        if (tableList != null) {
            List al = new ArrayList<Result>();
            List<String> al2 = new ArrayList<String>();

            for (String type : tableList) {
                if (commandStr.equalsIgnoreCase("DDL") || commandStr.equalsIgnoreCase("DDL_FILE")) {
                    ddlString = typeDAO.generateDDL(schema, type, (String) session.getAttribute("user_key"));
                    al2.add(ddlString);
                } else {
                    result = null;
                    result = typeDAO.simpletypeCommand(schema, type, commandStr,
                            (String) session.getAttribute("user_key"));
                    al.add(result);
                }
            }

            if (commandStr.equalsIgnoreCase("DDL")) {
                request.setAttribute("arrayresultddl", al2);
            } else if (commandStr.equalsIgnoreCase("DDL_FILE")) {
                response.setContentType(SAVE_CONTENT_TYPE);
                response.setHeader("Content-Disposition",
                        "attachment; filename=" + String.format(FILENAME, "TypeDDL"));

                ServletOutputStream out = response.getOutputStream();
                for (String ddl : al2) {
                    out.println(ddl);
                }

                out.close();
                return null;
            } else {
                model.addAttribute("arrayresult", al);
            }
        }

        types = typeDAO.retrieveTypeList(schema, null, (String) session.getAttribute("user_key"));
    }

    model.addAttribute("records", types.size());
    model.addAttribute("estimatedrecords", types.size());

    UserPref userPref = (UserPref) session.getAttribute("prefs");

    if (types.size() <= userPref.getRecordsToDisplay()) {
        model.addAttribute("types", types);
    } else {
        if (request.getParameter("startAtIndex") != null) {
            startAtIndex = Integer.parseInt(request.getParameter("startAtIndex"));
        }

        if (request.getParameter("endAtIndex") != null) {
            endAtIndex = Integer.parseInt(request.getParameter("endAtIndex"));
            if (endAtIndex > types.size()) {
                endAtIndex = types.size();
            }
        } else {
            endAtIndex = userPref.getRecordsToDisplay();
        }

        List subList = types.subList(startAtIndex, endAtIndex);
        model.addAttribute("types", subList);
    }

    model.addAttribute("startAtIndex", startAtIndex);
    model.addAttribute("endAtIndex", endAtIndex);

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

    model.addAttribute("chosenSchema", schema);

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

From source file:com.fullmetalgalaxy.server.AccountServlet.java

/**
 * try to connect an FMG (not google or other credential) user
 * @param p_request/*from  w w  w  .j  a  v  a 2s  .  c  om*/
 * @param p_response
 * @param params
 * @return false if connection failed and p_response is redirected. 
 * @throws IOException
 */
private boolean connectFmgUser(HttpServletRequest p_request, HttpServletResponse p_response,
        Map<String, String> params) throws IOException {
    String login = params.get("login");
    if (login == null || login.isEmpty()) {
        p_response.sendRedirect("/auth.jsp?msg=login ou mot de passe invalide");
        return false;
    }
    FmgDataStore ds = new FmgDataStore(true);
    Query<EbAccount> query = ds.query(EbAccount.class).filter("m_login", login);
    EbAccount account = query.get();
    if (account == null) {
        query = ds.query(EbAccount.class).filter("m_compactPseudo", ServerUtil.compactTag(login));
        account = query.get();
    }

    if (account == null) {
        p_response.sendRedirect("/auth.jsp?msg=login ou mot de passe invalide");
        return false;
    }
    login = account.getLogin();
    params.put("login", login);
    p_request.setAttribute("login", login);

    // if user is already connected as admin: don't check password and allow connect to another user
    if (!Auth.isUserAdmin(p_request, p_response)) {
        if (account.getAuthProvider() != AuthProvider.Fmg) {
            p_response.sendRedirect(Auth.getGoogleLoginURL(p_request, p_response));
            return false;
        }
        String password = params.get("password");
        if (password == null) {
            p_response.sendRedirect("/auth.jsp?msg=login ou mot de passe invalide");
            return false;
        }
        if (account == null || account.getPassword() == null || !account.getPassword().equals(password)) {
            p_response.sendRedirect("/auth.jsp?msg=login ou mot de passe invalide");
            return false;
        }
    }

    // all seams ok: connect user
    Auth.connectUser(p_request, login);
    return true;
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.DeletePageController.java

@Override
protected void doPost(HttpServletRequest rawRequest, HttpServletResponse resp)
        throws ServletException, IOException {
    if (!isAuthorizedToDisplayPage(rawRequest, resp, SimplePermission.MANAGE_MENUS.ACTION)) {
        return;/* w w  w  .  j a  v  a  2 s .  c o  m*/
    }
    removeStatements = ModelFactory.createDefaultModel();
    VitroRequest vreq = new VitroRequest(rawRequest);
    String pageUri = vreq.getParameter("pageURI");
    if (pageUri != null) {
        doDeletePage(pageUri, vreq, resp);
    }
    resp.sendRedirect(rawRequest.getContextPath() + REDIRECT_URL);
}

From source file:mvc.interceptor.AutorizadorInterceptor.java

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

    String uri = request.getRequestURI();
    String contextPath = request.getContextPath();

    if (uri.endsWith(contextPath) || uri.contains("index") || uri.contains("formLogin")
            || uri.contains("efetuaLogin") || uri.contains("listaTarefas") || uri.contains("resources")) {
        return true;
    }//from w w  w  .j  ava2 s .c o  m

    HttpSession session = request.getSession();

    if (session.getAttribute("usuarioLogado") != null) {
        return true;
    }

    response.sendRedirect("formLogin");

    return false;
}

From source file:Controllers.AddItem.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w ww.ja v  a  2 s.  com*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String name = null;
    String itemCode = null;
    String price = null;
    String quantity = null;
    String category = null;
    String image = null;
    HttpSession session = request.getSession(true);
    User user = (User) session.getAttribute("user");
    if (user == null) {
        response.sendRedirect("login");
        return;
    }
    //        request.getServletContext().getRealPath("/uploads");
    String path = request.getServletContext().getRealPath("/uploads");
    System.out.println(path);

    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    //                        new File(path).mkdirs();
                    File directory = new File(path + File.separator + fileName);
                    image = fileName;
                    item.write(directory);
                } else {
                    if ("name".equals(item.getFieldName())) {
                        name = item.getString();
                    } else if ("itemCode".equals(item.getFieldName())) {
                        itemCode = item.getString();
                    } else if ("price".equals(item.getFieldName())) {
                        price = item.getString();
                    } else if ("quantity".equals(item.getFieldName())) {
                        quantity = item.getString();
                    } else if ("category".equals(item.getFieldName())) {
                        category = item.getString();
                    }
                }
            }

            //File uploaded successfully
            System.out.println("done");
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    boolean status = ItemRepository.saveItem(name, itemCode, price, quantity, category, image, user);
    String message;
    if (status) {
        message = "Item saved successfully";
        response.sendRedirect("dashboard");
    } else {
        message = "Item not saved !!";
        request.setAttribute("message", message);
        request.getRequestDispatcher("dashboard/addItem.jsp").forward(request, response);
    }
}