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.qcadoo.mes.basic.controllers.WorkstationMultiUploadController.java

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

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

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(WorkstationAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(WorkstationAttachmentFields.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.netcracker.tss.web.servlet.customer.CustomerMMGServiceServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request// w w  w .j ava 2  s. c o  m
 * @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 {
    request.setCharacterEncoding("UTF-8");
    try {
        if (request.getParameter("addFrom") != null) {
            addAddressFrom(request);
            response.sendRedirect("/customer/orderpage");
        } else if (request.getParameter("addTo") != null) {
            addAddressTo(request);
            response.sendRedirect("/customer/orderpage");
        } else if (request.getParameter("deleteTo") != null || request.getParameter("deleteFrom") != null) {
            deleteAddress(request);
            response.sendRedirect("/customer/orderpage");
        } else {
            Date bookingTime = new Date();
            Date orderTime = DateParser.parseDate(request);
            if (orderTime.before(bookingTime)) {
                request.setAttribute("errorMessage",
                        "It is impossible to order taxi at the past! Please input the correct order time.");
                redirectToTaxiOrder(request, response);
                //                req.getRequestDispatcher("/customer/orderpage").forward(req, resp);
                //                resp.sendRedirect("/customer/orderpage?err=It is impossible to order taxi at the past! Please input the correct order time.");
            } else {
                User user = findCurrentUser();
                MeetMyGuestBeanLocal myGuestBeanLocal = getMeetMyGuestBean(request);
                TaxiOrderBeanLocal taxiOrderBeanLocal = getTaxiOrderBean(request);
                PriceBeanLocal priceBean = getPriceBean(request);
                float distance = 0;
                double price = 0;

                Route route = new Route(findCurrentUser().getUsername() + " Route");
                route.setDistance(distance);
                Address addFrom = toAddress(request.getParameter("fromAddr"), request);
                Address addTo = toAddress(request.getParameter("toAddr"), request);
                TaxiOrder taxiOrder = new TaxiOrder(AdditionalParameters.taxiOrderAddParameters(request));
                MapBeanLocal mapBean = getMapBean(request);
                distance = mapBean.calculateDistance(request.getParameter("fromAddr"),
                        request.getParameter("toAddr"));

                price = priceBean.calculatePrice(distance, DateParser.parseDate(request), taxiOrder,
                        UserUtils.findCurrentUser());

                taxiOrder.setBookingTime(bookingTime);
                taxiOrder.setOrderTime(orderTime);
                taxiOrder.setPrice(price);
                String guestName = request.getParameter("guestName");
                myGuestBeanLocal.addMeetMyGuestService(user, route, addFrom, addTo, taxiOrder, guestName);
                int latestTOId = taxiOrderBeanLocal.getTaxiOrderHistory(1, 1, user).get(0).getId();
                request.setAttribute("taxiOrderId", latestTOId);
                request.setAttribute("pageContent", "content/confirmation.jsp");
                request.getRequestDispatcher("/WEB-INF/views/customer/customer-template.jsp").forward(request,
                        response);
            }
        }
    } catch (Exception e) {
        Logger.getLogger(CustomerSoberServiceServlet.class.getName()).log(Level.SEVERE, e.getMessage(), e);
        request.setAttribute("errorMessage",
                "Sorry, we can not make this order! Please, check all input parameters ad try again.");
        redirectToTaxiOrder(request, response);
        //            response.sendRedirect(
        //                    "/customer/mmgServicePage?err=Sorry, we can not make this order! Please, check all input parameters ad try again.");
    }

}

From source file:com.qcadoo.mes.basic.controllers.SubassemblyMultiUploadController.java

@RequestMapping(value = "/getAttachmentForSubassembly.html", method = RequestMethod.GET)
public final void getAttachment(@RequestParam("id") final Long[] ids, HttpServletResponse response) {
    DataDefinition attachmentDD = dataDefinitionService.get(BasicConstants.PLUGIN_IDENTIFIER,
            BasicConstants.MODEL_SUBASSEMBLY_ATTACHMENT);
    Entity attachment = attachmentDD.get(ids[0]);
    InputStream is = fileService//from  w ww.j a v a  2  s  .  co  m
            .getInputStream(attachment.getStringField(SubassemblyAttachmentFields.ATTACHMENT));

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

        response.setHeader("Content-disposition",
                "inline; filename=" + attachment.getStringField(SubassemblyAttachmentFields.NAME));
        response.setContentType(
                fileService.getContentType(attachment.getStringField(SubassemblyAttachmentFields.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:net.incrementalism.tooter.LogInServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    if (isBlank(request.getParameter("userName"))) {
        request.setAttribute("error", "'User Name' must not be empty.");
    } else if (isBlank(request.getParameter("password"))) {
        request.setAttribute("error", "'Password' must not be empty.");
    } else {/*from   www . ja  va2  s. c o m*/
        try {
            setCurrentUser(request,
                    logInUser(request.getParameter("userName"), request.getParameter("password")));
            response.sendRedirect("/profile");
            return;
        } catch (LogInException e) {
            request.setAttribute("error", "Incorrect User Name or Password.");
        }
    }
    request.getRequestDispatcher("/logIn.jsp").include(request, response);
}

From source file:demo.oauth.client.controllers.AuthorizeResourceOwnerController.java

@RequestMapping("/authorizeResourceOwner")
public void handleRequest(@ModelAttribute(value = "oAuthParams") OAuthParams oAuthParams,
        HttpServletResponse response) throws Exception {

    String oauthToken = oAuthParams.getOauthToken();
    String resourceOwnerAuthorizationEndpoint = oAuthParams.getResourceOwnerAuthorizationEndpoint();
    if (resourceOwnerAuthorizationEndpoint == null || "".equals(resourceOwnerAuthorizationEndpoint)) {
        oAuthParams.setErrorMessage("Missing resource owner authorization URI");
    }/*from  ww w  .jav a  2 s  .  c o  m*/

    if (oauthToken == null || "".equals(oauthToken)) {
        oAuthParams.setErrorMessage("Missing oauth token");
    }

    response.sendRedirect(new StringBuilder().append(resourceOwnerAuthorizationEndpoint).append("?oauth_token=")
            .append(oauthToken).toString());
}

From source file:com.ci6225.marketzone.servlet.seller.ViewProductListServlet.java

/**
 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
 * response)//from w  ww  . ja v a2 s.  c o m
 */
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    try {
        User user = (User) request.getSession().getAttribute("user");
        List<Product> productList = productBean.getProductList(user.getUserId());
        request.setAttribute("productList", productList);
        RequestDispatcher rd = request.getRequestDispatcher("./jsp/seller/product_list.jsp");
        rd.forward(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        response.sendRedirect("./");
    }

}

From source file:io.muic.ooc.webapp.servlet.RegisterServlet.java

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String iusername = request.getParameter("username");
    String ipassword = request.getParameter("password");
    String ifirstname = request.getParameter("fname");
    if (!StringUtils.isBlank(iusername) && !StringUtils.isBlank(ipassword)
            && !StringUtils.isBlank(ifirstname)) {
        if (!db.readData().containsKey(iusername)) {
            db.insertDB(iusername, ipassword, ifirstname);
            response.sendRedirect("/login");
        } else {/*  ww w  .  ja v  a  2s.  c  o m*/
            String error = "Please choose another username. ";
            request.setAttribute("error", error);
            RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/signup.jsp");
            rd.include(request, response);
        }
    } else {
        String error = "Please fill in all the requirement form.";
        request.setAttribute("error", error);
        RequestDispatcher rd = request.getRequestDispatcher("WEB-INF/signup.jsp");
        rd.include(request, response);
    }
}

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

@RequestMapping(value = "/createfunction", method = RequestMethod.POST)
public String createFunctionAction(@ModelAttribute("functionAttribute") NewFunction functionAttribute,
        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 a  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;
            }
        }

    }

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

    String schema = functionAttribute.getSchemaName().trim();

    if (schema.length() == 0) {
        schema = (String) session.getAttribute("schema");
    }

    logger.debug("New Function schema name = " + schema);
    logger.debug("New Function name = " + functionAttribute.getFunctionName());

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

    if (submit != null) {
        if (submit.equalsIgnoreCase("Parameter(s)")) {
            int cols = Integer.parseInt(request.getParameter("numParams"));
            int numParams = Integer.parseInt((String) session.getAttribute("numParams"));

            numParams = numParams + cols;

            session.setAttribute("numParams", "" + numParams);
            model.addAttribute("numParams", numParams);
        } else {
            // build create HDFS Store SQL
            StringBuffer createFunction = new StringBuffer();

            createFunction
                    .append("CREATE FUNCTION " + schema + "." + functionAttribute.getFunctionName() + " \n");

            String[] parameterTypes = request.getParameterValues("parameter_type[]");
            String[] parameterNames = request.getParameterValues("parameter_name[]");
            String[] dataTypes = request.getParameterValues("data_type[]");
            String[] columnPrecision = request.getParameterValues("column_precision[]");

            logger.debug("parameterTypes = " + Arrays.toString(parameterTypes));
            logger.debug("parameterNames = " + Arrays.toString(parameterNames));
            logger.debug("dataTypes = " + Arrays.toString(dataTypes));
            logger.debug("columnPrecision = " + Arrays.toString(columnPrecision));

            int i = 0;
            int size = 0;

            if (parameterNames != null) {
                size = parameterNames.length;

                for (String parameterName : parameterNames) {
                    if (i == 0) {
                        createFunction.append("(");
                    }

                    createFunction.append(parameterName + " " + dataTypes[i]);
                    if (columnPrecision[i].length() != 0) {
                        createFunction.append("(" + columnPrecision[i] + ")");
                    }

                    i++;
                    if (i < size) {
                        createFunction.append(", \n");
                    }
                }

                if (i >= 1) {
                    createFunction.append(") \n");
                }
            }

            createFunction.append("RETURNS " + functionAttribute.getReturnType());
            if (functionAttribute.getReturnPrecision().trim().length() != 0) {
                createFunction.append("(" + functionAttribute.getReturnPrecision() + ") \n");
            } else {
                createFunction.append(" \n");
            }

            if (!checkIfParameterEmpty(request, "language")) {
                createFunction.append("LANGUAGE " + functionAttribute.getLanguage() + " \n");
            }

            createFunction.append("EXTERNAL NAME '" + functionAttribute.getExternalName() + "' \n");

            if (!checkIfParameterEmpty(request, "parameterStyle")) {
                createFunction.append("PARAMETER STYLE " + functionAttribute.getParameterStyle() + " \n");
            }

            if (!checkIfParameterEmpty(request, "sqlAccess")) {
                createFunction.append(functionAttribute.getSqlAccess() + " \n");
            }

            if (!checkIfParameterEmpty(request, "ifNull")) {
                createFunction.append(functionAttribute.getIfNull() + " \n");
            }

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

                logger.debug("Creating Function as -> " + createFunction.toString());

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

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

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

    }

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

From source file:com.company.project.web.controller.service.CustomAuthenticationSuccessHandler.java

@Override
public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
        Authentication authentication) throws IOException, ServletException {
    SecurityContext context = SecurityContextHolder.getContext();
    Object principalObj = context.getAuthentication().getPrincipal();
    String principal = ((UserDetails) principalObj).getUsername();
    // Create the User Cookie    
    if (((UserDetails) principalObj).getAuthorities() != null && ((UserDetails) principalObj).getAuthorities()
            .contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
        response.sendRedirect("/admin");
    } else {//from  ww w. j  ava 2  s .c  o  m
        response.sendRedirect("/welcome");
    }
}

From source file:ke.co.tawi.babblesms.server.servlet.accountmngmt.EditContact.java

/**
 *
 * @param request/*ww  w .  j  a v  a  2 s  . c om*/
 * @param response
 * @throws ServletException, IOException
 */

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession session = request.getSession(true);

    String username = (String) session.getAttribute(SessionConstants.ACCOUNT_SIGN_IN_KEY);
    if (StringUtils.isEmpty(username)) {
        response.sendRedirect("../index.jsp");
    }
    Account account = new Account();

    Element element;
    if ((element = accountCache.get(username)) != null) {
        account = (Account) element.getObjectValue();
    }
    String contactname = request.getParameter("name").trim();
    String contactstatusuuid = request.getParameter("statusuuid").trim();
    String description = request.getParameter("description").trim();

    String[] groupArray = request.getParameterValues("groupselected[]");
    String cuuid = request.getParameter("uuid").trim();
    String[] phonenumArray = request.getParameterValues("phone1[]");

    String[] emailArray = request.getParameterValues("email[]");
    String[] networkArray = request.getParameterValues("network[]");

    if (contactname.equals("") || phonenumArray.equals("")) {
        session.setAttribute("fail", ERROR_NO_NAME);
    }

    else {

        boolean Contact = saveContact(cuuid, contactname, description, account);
        boolean Phone = savePhone(phonenumArray, networkArray, cuuid, contactstatusuuid);
        boolean Email = saveEmail(cuuid, emailArray);
        boolean Group = saveGroup(account, groupArray);

        if (Contact == true && Phone == true && Email == true && Group == true) {
            session.setAttribute("success", "Saved Successfully!!");

        } else {
            session.setAttribute("fail", "An Error occurred, Please try Again!!");
        }
    }

    response.sendRedirect("contact.jsp");
}