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:com.bitranger.parknshop.seller.controller.SellerShowCtrl.java

@RequestMapping(value = "/seller/record", method = RequestMethod.GET)
public void showOrders(HttpServletRequest request, HttpServletResponse response) throws IOException {

    PsSeller seller = (PsSeller) request.getSession().getAttribute("currentSeller");
    if (seller == null) {
        //         http://bowen_ultimate:8080/C1_ParknShop/seller/sellerlogin
        response.sendRedirect("/C1_ParknShop/sellerLogin.jsp");
        return;//w  ww.j  av  a2s  .c  om
    }

    Set<PsShop> shops = seller.getPsShops();
    Iterator<PsShop> it = shops.iterator();
    List<PsOrder> orders = new ArrayList<PsOrder>();
    List<SellerOrderDisplay> orderDisplays = new ArrayList<SellerOrderDisplay>();

    //List<ROrderItem> orderItems = new ArrayList<ROrderItem>();

    while (it.hasNext()) {
        PsShop shop = it.next();
        orders.addAll(psOrderDao.findByShopId(shop.getId()));
    }

    for (PsOrder order : orders) {

        Iterator<ROrderItem> iterator = order.getROrderItems().iterator();
        while (iterator.hasNext()) {

            ROrderItem orderItem = iterator.next();

            SellerOrderDisplay sellerOrderDisplay = new SellerOrderDisplay();
            sellerOrderDisplay.setId(order.getId());
            sellerOrderDisplay.setItemPic(orderItem.getPsItem().getUrlPicture());
            sellerOrderDisplay.setItemName(orderItem.getPsItem().getName());
            sellerOrderDisplay.setSoldTime(order.getTimeCreated());
            sellerOrderDisplay.setPrice(orderItem.getPsItem().getPrice());
            sellerOrderDisplay.setQuantity(orderItem.getQuantitiy());
            sellerOrderDisplay.setBuyerName(order.getPsCustomer().getName());
            sellerOrderDisplay.setState(order.getStatus());
            sellerOrderDisplay.setAddress(order.getPsRecipient().getAddresss());
            sellerOrderDisplay.setPhone(order.getPsRecipient().getPhoneNumber());

            orderDisplays.add(sellerOrderDisplay);
        }
        //orderItems.addAll(iROrderItemDAO.findByOrderId(order.getId()));
    }

    System.out.println(orderDisplays.size());

    /*JsonConfig jsonConfig = new JsonConfig();
     jsonConfig.setIgnoreDefaultExcludes(false);
    jsonConfig.setExcludes(new String[]{"psShop"});
    jsonConfig.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT);*/

    /*jsonConfig.registerJsonValueProcessor(ROrderItem.class,
    new ObjectJsonValueProcessor(new String[]{"quantity"}, ROrderItem.class));*/

    JSONArray jsonArray = JSONArray.fromObject(orderDisplays);

    System.out.println(jsonArray.toString());
    PrintWriter out = response.getWriter();
    out.write(jsonArray.toString());
    out.flush();
    out.close();

}

From source file:com.qcadoo.view.internal.controllers.FileResolverController.java

@RequestMapping(value = "{tenantId:\\d+}/{firstLevel:\\d+}/{secondLevel:\\d+}/{fileName}", method = RequestMethod.GET)
public void resolve(final HttpServletRequest request, final HttpServletResponse response,
        @PathVariable("tenantId") final String tenantId) {
    String path = fileService.getPathFromUrl(request.getRequestURI());

    boolean removeFileAfterProcessing = request.getParameterMap().containsKey("clean");

    if (Integer.valueOf(tenantId) != MultiTenantUtil.getCurrentTenantId()) {
        try {//  w  w w.  j  a  v a 2s  . co m
            response.sendRedirect("/error.html?code=404");
        } catch (IOException e) {
            throw new IllegalStateException(e.getMessage(), e);
        }
    }

    InputStream input = null;

    try {
        input = fileService.getInputStream(path);

        if (input == null) {
            response.sendRedirect("/error.html?code=404");
        } else {
            OutputStream output = response.getOutputStream();

            int bytes = IOUtils.copy(input, output);

            response.setHeader("Content-disposition", "inline; filename=" + fileService.getName(path));
            response.setContentType(fileService.getContentType(path));
            response.setContentLength(bytes);

            output.flush();
        }
    } catch (IOException e) {
        IOUtils.closeQuietly(input);
        throw new IllegalStateException(e.getMessage(), e);
    }

    if (removeFileAfterProcessing) {
        fileService.remove(path);
    }
}

From source file:fina.usuario.servlet.usuarioServlet.java

private void cerrarSesion(HttpServletRequest request, HttpServletResponse response) {
    HttpSession session = request.getSession(true);
    session.invalidate();/* ww  w  .ja  va 2s.co  m*/
    try {
        response.sendRedirect("index.jsp");
    } catch (Exception e) {
    }
}

From source file:com.ntscorp.notice.interceptor.SessionInterceptor.java

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
        throws Exception {
    logger.info("HomeController   ");

    AuthCheck authCheck = ((HandlerMethod) handler).getMethodAnnotation(AuthCheck.class);

    if (authCheck != null) {
        HttpSession session = request.getSession();
        String userId = (String) session.getAttribute("userId");

        if (userId == null) {
            response.sendRedirect("login/form"); //? userid ?  ?? ? ...
            return false;
        }/* w  w w. j  a  v  a2s  .  c  o  m*/
    }

    return true;
}

From source file:fi.helsinki.opintoni.security.CustomAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    AppUser appUser = (AppUser) authentication.getPrincipal();

    try {/*from w ww  .j a v  a 2 s  . c  o m*/
        syncUserWithDatabase(appUser);

        addLanguageCookie(appUser, response);
        addLastLoginCookie(response);
        addHasLoggedInCookie(response);

        response.sendRedirect("/");

    } catch (OodiIntegrationException e) {
        response.sendRedirect("/error/maintenance");
    }

}

From source file:is.idega.idegaweb.egov.application.servlet.filter.ApplicationUrlRedirector.java

@Override
public void doFilter(ServletRequest srequest, ServletResponse sresponse, FilterChain chain)
        throws IOException, ServletException {
    HttpServletRequest request = (HttpServletRequest) srequest;
    HttpServletResponse response = (HttpServletResponse) sresponse;
    boolean doRedirect = getIfDoRedirect(request);
    if (doRedirect) {
        String newUrl = getNewRedirectURL(request, response);
        response.sendRedirect(newUrl);
    } else {//from   w  ww .ja v  a2  s. c o m
        chain.doFilter(srequest, sresponse);
    }
}

From source file:com.evolveum.midpoint.web.security.MidPointAccessDeniedHandler.java

@Override
public void handle(HttpServletRequest request, HttpServletResponse response,
        AccessDeniedException accessDeniedException) throws IOException, ServletException {
    if (response.isCommitted()) {
        return;/*from  ww  w .  j a va2s  . c o m*/
    }

    // handle invalid csrf token exception gracefully when user tries to log in/out with expired exception
    if (isLoginLogoutRequest(request) && (accessDeniedException instanceof MissingCsrfTokenException)) {
        response.sendRedirect(request.getContextPath());
        return;
    }

    defaultHandler.handle(request, response, accessDeniedException);
}

From source file:com.palantir.stash.disapprove.servlet.DisapprovalServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

    final String user = authenticateUser(req, res);
    if (user == null) {
        // not logged in, redirect
        res.sendRedirect(lup.getLoginUri(getUri(req)).toASCIIString());
        return;//from  w w  w .  j  a  va2s .  co  m
    }

    final String REQ_PARAMS = "repoId(int), prId(long), disapproved(true|false)";
    final Integer repoId;
    final Long prId;
    try {
        repoId = Integer.valueOf(req.getParameter("repoId"));
        prId = Long.valueOf(req.getParameter("prId"));
    } catch (NumberFormatException e) {
        throw new IllegalArgumentException("The required paramaters are: " + REQ_PARAMS, e);
    }
    final PullRequest pr = pullRequestService.getById(repoId, prId);
    final Repository repo = pr.getToRef().getRepository();

    PullRequestDisapproval prd;
    DisapprovalConfiguration dc;
    try {
        prd = pm.getPullRequestDisapproval(pr);
        dc = pm.getDisapprovalConfiguration(repo);
    } catch (SQLException e) {
        throw new ServletException(e);
    }

    boolean oldDisapproval = prd.isDisapproved();
    boolean disapproval;

    String disapproved = req.getParameter("disapproved");
    if (disapproved != null && disapproved.equalsIgnoreCase("true")) {
        disapproval = true;
    } else if (disapproved != null && disapproved.equalsIgnoreCase("false")) {
        disapproval = false;
    } else {
        throw new IllegalArgumentException("The required parameters are: " + REQ_PARAMS);
    }
    Writer w = res.getWriter();
    res.setContentType("application/json;charset=UTF-8");
    try {
        processDisapprovalChange(repo, user, prd, oldDisapproval, disapproval);
        //res.setContentType("text/html;charset=UTF-8");
        w.append(new JSONObject(ImmutableMap.of("disapproval", prd.isDisapproved(), "disapprovedBy",
                prd.getDisapprovedBy(), "enabledForRepo", dc.isEnabled())).toString());
    } catch (IllegalStateException e) {
        w.append(new JSONObject(ImmutableMap.of("error", e.getMessage())).toString());
        res.setStatus(401);
    } finally {
        w.close();
    }
}

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

@RequestMapping(value = "/creatediskstore", method = RequestMethod.POST)
public String createHDFSStoreAction(@ModelAttribute("diskStoreAttribute") NewDiskStore diskStoreAttribute,
        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 {/* w  ww  .j  ava2s . 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;
            }
        }

    }

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

    String diskStoreName = diskStoreAttribute.getDiskStoreName();

    logger.debug("New Disk Store Name = " + diskStoreName);

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

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

        createDiskStore.append("create DISKSTORE " + diskStoreName + " \n");

        if (!checkIfParameterEmpty(request, "maxLogSize")) {
            createDiskStore.append("MAXLOGSIZE " + diskStoreAttribute.getMaxLogSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "autoCompact")) {
            createDiskStore.append("AUTOCOMPACT " + diskStoreAttribute.getAutoCompact() + " \n");
        }

        if (!checkIfParameterEmpty(request, "allowForceCompaction")) {
            createDiskStore
                    .append("ALLOWFORCECOMPACTION " + diskStoreAttribute.getAllowForceCompaction() + " \n");
        }

        if (!checkIfParameterEmpty(request, "compactionThreshold")) {
            createDiskStore
                    .append("COMPACTIONTHRESHOLD " + diskStoreAttribute.getCompactionThreshold() + " \n");
        }

        if (!checkIfParameterEmpty(request, "timeInterval")) {
            createDiskStore.append("TIMEINTERVAL " + diskStoreAttribute.getTimeInterval() + " \n");
        }

        if (!checkIfParameterEmpty(request, "writeBufferSize")) {
            createDiskStore.append("WRITEBUFFERSIZE " + diskStoreAttribute.getWriteBufferSize() + " \n");
        }

        if (!checkIfParameterEmpty(request, "additionalParams")) {
            createDiskStore.append(diskStoreAttribute.getAdditionalParams());
        }

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

            logger.debug("Creating disk store as -> " + createDiskStore.toString());

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

            model.addAttribute("result", result);

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

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

    }

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

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

@RequestMapping(value = "/creategatewayreceiver", method = RequestMethod.POST)
public String createGatewayReceiverAction(
        @ModelAttribute("gatewayReceiverAttribute") NewGatewayReceiver gatewayReceiverAttribute, 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 v  a2 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;
            }
        }

    }

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

    String gatewayReceiverName = gatewayReceiverAttribute.getGatewayReceiverName();

    logger.debug("New Gateway Receiver Name = " + gatewayReceiverName);

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

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

        createGatewayReceiver.append("CREATE GATEWAYRECEIVER " + gatewayReceiverName + " (\n");

        if (!checkIfParameterEmpty(request, "bindAddress")) {
            createGatewayReceiver.append("BINDADDRESS '" + gatewayReceiverAttribute.getBindAddress() + "' \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "startPort")) {
            createGatewayReceiver.append("STARTPORT " + gatewayReceiverAttribute.getStartPort() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "endPort")) {
            createGatewayReceiver.append("ENDPORT " + gatewayReceiverAttribute.getEndPort() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "socketBufferSize")) {
            createGatewayReceiver
                    .append("SOCKETBUFFERSIZE " + gatewayReceiverAttribute.getSocketBufferSize() + " \n");
            needCloseBracket = true;
        }

        if (!checkIfParameterEmpty(request, "maxTimeBetweenPings")) {
            createGatewayReceiver
                    .append("MAXTIMEBETWEENPINGS " + gatewayReceiverAttribute.getMaxTimeBetweenPings() + " \n");
            needCloseBracket = true;
        }

        if (needCloseBracket) {
            createGatewayReceiver.append(") ");
        }

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

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

            logger.debug("Creating gateway receiver as -> " + createGatewayReceiver.toString());

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

            model.addAttribute("result", result);

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

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

    }

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