Example usage for javax.servlet RequestDispatcher forward

List of usage examples for javax.servlet RequestDispatcher forward

Introduction

In this page you can find the example usage for javax.servlet RequestDispatcher forward.

Prototype

public void forward(ServletRequest request, ServletResponse response) throws ServletException, IOException;

Source Link

Document

Forwards a request from a servlet to another resource (servlet, JSP file, or HTML file) on the server.

Usage

From source file:controller.uploadPergunta7ArquivoAjuste.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  www  .ja  va  2 s.co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    String idLocal = (String) request.getParameter("idLocal");
    String expressaoModeloVolumePadrao = (String) request.getParameter("expressaoModeloVolumePadrao");

    String name = "";
    //process only if its multipart content
    if (ServletFileUpload.isMultipartContent(request)) {
        try {
            List<FileItem> multiparts = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);

            for (FileItem item : multiparts) {
                if (!item.isFormField()) {
                    name = new File(item.getName()).getName();
                    //                        item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
                    item.write(new File(AbsolutePath + File.separator + name));
                }
            }

            //File uploaded successfully
            request.setAttribute("message", "File Uploaded Successfully");
        } catch (Exception ex) {
            request.setAttribute("message", "File Upload Failed due to " + ex);
        }

    } else {
        request.setAttribute("message", "Sorry this Servlet only handles file upload request");
    }
    expressaoModeloVolumePadrao = expressaoModeloVolumePadrao.replace("+", "%2B");
    RequestDispatcher view = getServletContext().getRequestDispatcher("/novoLocalPergunta7?id=" + idLocal
            + "&nomeArquivoAjuste=" + name + "&expressaoModeloVolumePadrao=" + expressaoModeloVolumePadrao);
    view.forward(request, response);

    //        request.getRequestDispatcher("/novoLocalPergunta3?id="+idLocal+"&fupload=1&nomeArquivo="+name).forward(request, response);
    // request.getRequestDispatcher("/novoLocalPergunta4?id="+idLocal+"&nomeArquivo="+name).forward(request, response);

}

From source file:org.apache.hadoop.hdfsproxy.ProxyForwardServlet.java

/** {@inheritDoc} */
public void forwardRequest(HttpServletRequest request, HttpServletResponse response, ServletContext context,
        String pathInfo) throws IOException, ServletException {
    String path = buildForwardPath(request, pathInfo);
    RequestDispatcher dispatcher = context.getRequestDispatcher(path);
    if (dispatcher == null) {
        LOG.info("There was no such dispatcher: " + path);
        response.sendError(HttpServletResponse.SC_NO_CONTENT);
        return;/*from w  w w .j  a v a  2s . c o  m*/
    }
    dispatcher.forward(request, response);
}

From source file:edu.lternet.pasta.portal.SavedDataServlet.java

/**
 * The doPost method of the servlet. <br>
 * //w  ww. j  av  a2s.  co m
 * This method is called when a form has its tag value method equals to post.
 * 
 * @param request
 *          the request send by the client to the server
 * @param response
 *          the response send by the server to the client
 * @throws ServletException
 *           if an error occurred
 * @throws IOException
 *           if an error occurred
 */
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    HttpSession httpSession = request.getSession();
    String forward = (String) request.getParameter("forward");
    String startStr = (String) request.getParameter("start");
    String rowsStr = (String) request.getParameter("rows");
    String sort = (String) request.getParameter("sort");

    if (sort == null || sort.equals("")) {
        sort = String.format("%s,%s", Search.PACKAGEID_SORT, Search.SORT_ORDER_ASC);
    }

    if (forward == null)
        forward = "savedData.jsp";

    String uid = (String) httpSession.getAttribute("uid");
    if (uid == null || uid.isEmpty()) {
        uid = "public";
    }

    String message = null;
    if (uid.equals("public")) {
        message = LOGIN_WARNING;
        forward = "./login.jsp";
        request.setAttribute("message", message);
        request.setAttribute("from", "savedDataServlet");
    } else {
        String operation = (String) request.getParameter("operation"); // "save" or "unsave"
        String packageId = (String) request.getParameter("packageId");
        SavedData savedData = new SavedData(uid);

        /*
         * First, execute any operations that change the state of the saved data
         */
        if (operation != null && packageId != null) {
            EmlPackageIdFormat emlPackageIdFormat = new EmlPackageIdFormat();
            EmlPackageId emlPackageId = emlPackageIdFormat.parse(packageId);
            String scope = emlPackageId.getScope();
            Integer identifier = emlPackageId.getIdentifier();
            Integer revision = emlPackageId.getRevision();

            if (operation.equals("save")) {
                savedData.addDocid(scope, identifier, revision);
            } else if (operation.equals("unsave")) {
                savedData.removeDocid(scope, identifier);
            }
        }

        /*
         * If we are forwarding to the saved data page, update the HTML
         * to be displayed
         */
        if (forward != null && forward.equals("savedData.jsp")) {
            String html = "<p>There are no data packages on your data shelf.</p>";
            String termsListHTML = "";
            String xml = null;
            response.setContentType("text/html");
            try {
                xml = savedData.getSavedDataXML(startStr, rowsStr, sort);
                if (xml != null) {
                    httpSession.setAttribute("termsListHTML", termsListHTML);
                    boolean isSavedDataPage = true;
                    ResultSetUtility resultSetUtility = new ResultSetUtility(xml, sort, savedData,
                            isSavedDataPage);
                    html = resultSetUtility.xmlToHtmlTable(cwd + xslpath);
                }
                request.setAttribute("searchresult", html);
            } catch (Exception e) {
                handleDataPortalError(logger, e);
            }
        }
    }

    /*
     * Forward to login.jsp or savedData.jsp, but not to other values because
     * they use AJAX and we don't want a page refresh
     */
    if (forward != null && !forward.equals("") && !forward.equals("savedData")
            && !forward.equals("simpleSearch")) {
        RequestDispatcher requestDispatcher = request.getRequestDispatcher(forward);
        requestDispatcher.forward(request, response);
    }
}

From source file:br.com.wavii.securyti.JsfLoginUrlAuthenticationEntryPoint.java

/**
 * Performs the redirect (or forward) to the login form URL.
 *///from w  w w .j  a  v  a  2 s  . co  m
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    String redirectUrl = null;

    if (useForward) {

        if (forceHttps && "http".equals(request.getScheme())) {
            // First redirect the current request to HTTPS.
            // When that request is received, the forward to the login page
            // will be used.
            redirectUrl = buildHttpsRedirectUrlForRequest(request);
        }

        if (redirectUrl == null) {
            String loginForm = determineUrlToUseForThisRequest(request, response, authException);

            if (logger.isDebugEnabled()) {
                logger.debug("Server side forward to: " + loginForm);
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);

            dispatcher.forward(request, response);

            return;
        }
    } else {
        // redirect to login page. Use https if forceHttps true

        redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);

    }

    redirectStrategy.sendRedirect(request, response, redirectUrl);
}

From source file:Controller.ControllerCustomers.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  ww w. j a v  a 2  s .  c  o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    try {
        String action = request.getParameter("action");
        if (action.equals("Login")) {
            String user = request.getParameter("txtId");
            String pass = request.getParameter("txtpass");
            Customers ct = new Customers();
            String anh = ct.anh(user);
            boolean check = ct.checkLogin(user, pass);
            String url = "error.jsp";
            if (check) {
                if (ct.role(user)) {
                    RequestDispatcher rd = request.getRequestDispatcher("Admin.jsp");
                    rd.forward(request, response);
                } else {

                    url = "index_Cus_2.jsp";
                    HttpSession session = request.getSession(true);
                    session.setAttribute("User", user);
                    session.setAttribute("Image", anh);
                    //                   <%

                    CartDao listsp = new CartDao();
                    List<Cart> list = CartDao.layDanhSachCart(user);
                    session.setAttribute("list", list);
                    //      %>

                }

            }
            RequestDispatcher rd = request.getRequestDispatcher(url);
            rd.forward(request, response);

        } else if (action.equals("FIND")) {
            String username = request.getParameter("txtusername");
            CustomerDAO cusdao = new CustomerDAO();
            List<Customer> list = new ArrayList<Customer>();
            list = cusdao.layDanhSachKhachHang(username);
            request.setAttribute("listKH", list);
            RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
            rd.forward(request, response);

        } else if (action.equals("DELETE")) {
            String username = request.getParameter("txtusername");
            boolean delete = CustomerDAO.XoaKhachHang(username);
            if (delete) {
                RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                rd.forward(request, response);

            }

        } else if (action.equals("Edit")) {
            String username = request.getParameter("txtusername");
            String password = request.getParameter("txtpassword");
            String hoten = request.getParameter("txthoten");
            String gioitinh = request.getParameter("txtgioitinh");
            String email = request.getParameter("txtemail");
            String role = request.getParameter("txtrole");
            String anh = request.getParameter("txtanh");
            Customer cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
            request.setAttribute("Cus", cus);
            RequestDispatcher rd = request.getRequestDispatcher("editCustomer.jsp");
            rd.forward(request, response);

        }
    } catch (Exception e) {
        e.printStackTrace();

    }

}

From source file:feedme.controller.OrderCompleteServlet.java

/**
 * Handles the HTTP <code>GET</code> method.
 *
 * @param request servlet request//w w  w.  j a va 2  s .  c  om
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    processRequest(request, response);

    AuthenticatUser customer = (AuthenticatUser) request.getSession().getAttribute("AuthenticatUser");//getting the customer from the session
    try {//check if its a customer 
        if (customer != null && PasswordEncryptionService.authenticate(Integer.toString(0),
                customer.getEncrypRole(), "Customer".getBytes())) {
            request.setAttribute("customer",
                    (Customer) new DbUsersManagement().getUserById(customer.getUserId()));
        }
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InvalidKeySpecException ex) {
        Logger.getLogger(OrderCompleteServlet.class.getName()).log(Level.SEVERE, null, ex);
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher("website/complete_order.jsp");//displays the customer a jsp file
    dispatcher.forward(request, response);

}

From source file:org.shredzone.commons.view.impl.ViewServiceImpl.java

@Override
public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception {
    String path = req.getPathInfo();
    if (path == null) {
        path = "";
    }//from   www  . j  a v  a  2s.c  om

    interceptors.forEach(it -> it.onRequest(req, resp));

    String renderViewName = null;

    try {
        ViewContext context = getViewContext();
        context.putTypedArgument(ServletContext.class, servletContext);
        context.putTypedArgument(HttpServletResponse.class, resp);
        renderViewName = invokeView(path);
    } catch (ErrorResponseException ex) {
        if (log.isDebugEnabled()) {
            StringBuilder sb = new StringBuilder();
            sb.append("View handler returned HTTP status ").append(ex.getResponseCode());
            if (ex.getMessage() != null) {
                sb.append(" (").append(ex.getMessage()).append(')');
            }
            sb.append(" for path '").append(path).append('\'');
            log.debug(sb.toString());
        }

        for (ViewInterceptor interceptor : interceptors) {
            if (interceptor.onErrorResponse(ex, req, resp)) {
                return;
            }
        }

        if (ex.getMessage() != null) {
            resp.sendError(ex.getResponseCode(), ex.getMessage());
        } else {
            resp.sendError(ex.getResponseCode());
        }
        return;
    }

    if (renderViewName != null) {
        for (ViewInterceptor interceptor : interceptors) {
            String newViewName = interceptor.onRendering(renderViewName, req, resp);
            if (newViewName != null) {
                renderViewName = newViewName;
            }
        }

        String fullViewPath = getTemplatePath(renderViewName);
        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(fullViewPath);
        dispatcher.forward(req, resp);
    }
}

From source file:edu.ncsu.lib.browse.Browse.java

private void dispatchError(HttpServletRequest request, HttpServletResponse response) {
    RequestDispatcher errDispatcher = request.getRequestDispatcher("jsp/error.jsp");
    try {//w  ww.ja v a  2 s.  c o  m
        errDispatcher.forward(request, response);
    } catch (Exception e) {
        System.out.println("Error forwarding to error.jsp");
        e.printStackTrace();
    }
}

From source file:Controller.ControllerCustomers.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*w w w  . jav  a 2s  .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 {
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {

    } else {
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        List items = null;
        try {
            items = upload.parseRequest(request);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Iterator iter = items.iterator();
        Hashtable params = new Hashtable();
        String fileName = null;
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();
            if (item.isFormField()) {
                params.put(item.getFieldName(), item.getString());
            } else {

                try {
                    String itemName = item.getName();
                    fileName = itemName.substring(itemName.lastIndexOf("\\") + 1);
                    String RealPath = getServletContext().getRealPath("/") + "upload\\" + fileName;
                    String username = (String) params.get("txtusername");
                    String password = (String) params.get("txtpassword");
                    String hoten = (String) params.get("txthoten");
                    String gioitinh = (String) params.get("txtgioitinh");
                    String email = (String) params.get("txtemail");
                    String role = (String) params.get("txtrole");
                    String anh = (String) params.get("txtanh");
                    //Update  product
                    if (fileName.equals("")) {

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role, anh);
                        CustomerDAO.SuaThongTinKhachHang(Cus);
                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);

                    } else {
                        // bat dau ghi file
                        File savedFile = new File(RealPath);
                        item.write(savedFile);
                        //ket thuc ghi

                        Customer Cus = new Customer(username, password, hoten, gioitinh, email, role,
                                "upload\\" + fileName);
                        CustomerDAO.SuaThongTinKhachHang(Cus);

                        RequestDispatcher rd = request.getRequestDispatcher("CustomerDao.jsp");
                        rd.forward(request, response);
                    }

                } catch (Exception e) {
                    System.out.println(e);
                    RequestDispatcher rd = request.getRequestDispatcher("InformationError.jsp");
                    rd.forward(request, response);
                }
            }

        }
    }

}

From source file:br.com.gerenciapessoal.security.JsfLoginUrlAuthenticationEntryPoint.java

/**
 * Performs the redirect (or forward) to the login form URL.
 *
 * @param request//ww w .  ja v a  2  s  .c  o  m
 * @param response
 * @param authException
 * @throws java.io.IOException
 * @throws javax.servlet.ServletException
 */
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

    String redirectUrl = null;

    if (useForward) {

        if (forceHttps && "http".equals(request.getScheme())) {
            // First redirect the current request to HTTPS.
            // When that request is received, the forward to the login page will be used.
            redirectUrl = buildHttpsRedirectUrlForRequest(request);
        }

        if (redirectUrl == null) {
            String loginForm = determineUrlToUseForThisRequest(request, response, authException);

            if (logger.isDebugEnabled()) {
                logger.debug("Server side forward to: " + loginForm);
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(loginForm);

            dispatcher.forward(request, response);

            return;
        }
    } else {
        // redirect to login page. Use https if forceHttps true

        redirectUrl = buildRedirectUrlToLoginPage(request, response, authException);

    }

    redirectStrategy.sendRedirect(request, response, redirectUrl);
}