Example usage for javax.servlet ServletContext getRequestDispatcher

List of usage examples for javax.servlet ServletContext getRequestDispatcher

Introduction

In this page you can find the example usage for javax.servlet ServletContext getRequestDispatcher.

Prototype

public RequestDispatcher getRequestDispatcher(String path);

Source Link

Document

Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.

Usage

From source file:org.iterx.miru.support.servlet.HttpDispatcherServlet.java

public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    assert (dispatcher != null) : "dispatcher == null";
    assert (processingContextFactory != null) : "processingContextFactory == null";

    try {/*from w  w  w .ja v a 2 s  . c  o m*/
        ProcessingContext<HttpServletRequestContext, HttpServletResponseContext> processingContext;
        HttpServletResponseContext responseContext;
        HttpServletRequestContext requestContext;

        processingContext = processingContextFactory.getProcessingContext(
                requestContext = new HttpServletRequestContext(request),
                responseContext = new HttpServletResponseContext(response));

        switch (dispatcher.dispatch(processingContext)) {
        case DONE:
            requestContext.close();
            responseContext.close();
            break;
        case OK:
        case DECLINE:
            break;
        case ERROR:
            responseContext.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            break;
        default:
            break;
        }
        ;
    } catch (RedirectEvent redirect) {
        URI uri;

        if ((uri = redirect.getURI()).getScheme() == null) {
            ServletContext servletContext;
            servletContext = (getServletConfig().getServletContext());

            (servletContext.getRequestDispatcher(uri.getPath())).forward(request, response);
        } else
            response.sendRedirect(uri.toString());
    } catch (ErrorEvent error) {
        String url;

        url = (request.getRequestURL()).toString();
        LOGGER.info("Error processing [" + url + "]", error);
        response.setStatus(error.getStatus());
    } catch (Exception e) {
        String url;

        url = (request.getRequestURL()).toString();
        LOGGER.error("Failed to process [" + url + "]", e);
        throw new ServletException("Request [" + url + "] failed.", e);
    }
}

From source file:com.ikon.servlet.admin.CronTabServlet.java

/**
 * List registered reports/*from www  .  ja v a  2  s. com*/
 */
private void list(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("list({}, {})", new Object[] { request, response });
    ServletContext sc = getServletContext();
    List<CronTab> list = CronTabDAO.findAll();
    sc.setAttribute("crontabs", list);
    sc.getRequestDispatcher("/admin/crontab_list.jsp").forward(request, response);
    log.debug("list: void");
}

From source file:Servlet.BAC_UploadInvitationToBid.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from  ww  w  . ja va 2 s  .  com*/
 *
 * @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, ParseException {
    response.setContentType("text/html;charset=UTF-8");

    try {

        InputStream inputStream = null;

        String category = null;

        ArrayList<String> files = new ArrayList<String>();
        String id2 = "";

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {
                //ArrayList<String> 

                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

                String id = null;
                String title = null;

                File path = null;
                File uploadedFiles = null;
                String fileName = null;

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();

                    if (item.isFormField()) {

                        //Returns the string inside the field
                        String value = item.getString();
                        //returns the name of the field
                        String value2 = item.getFieldName();

                        if (value2.equals("projectId")) {
                            id = value;
                            id2 = value;
                        }
                        if (value2.equals("projectName")) {
                            title = value;
                        }

                    }

                    if (!item.isFormField()) {
                        fileName = item.getName();
                        String root = getServletContext().getRealPath("/");

                        //path where the file will be stored
                        path = new File("D:\\Development\\NetBeans\\Projects\\Cogito\\Upload"
                                + "/Bids and Awards Department" + "/Invitations to bid" + "/" + title
                                + " invitation");
                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        uploadedFiles = new File(path + "/" + fileName);
                        item.write(uploadedFiles);
                        files.add(fileName);

                    }
                }

                BACDAO bacdao = new BACDAO();
                OCPDDAO oc = new OCPDDAO();
                Project project = oc.getAllProjectDetails(id);

                bacdao.changeBACStatus1(id);

                InvitationToBid invite = new InvitationToBid(0, fileName, null, project,
                        "chrome-extension://nhcgkapmceenhknicldaiaplpkpmicmc/" + "Bids and Awards Department"
                                + "/Invitations to bid" + "/" + title + " invitation");
                bacdao.uploadInvitation(invite);

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                Logger.getLogger(BAC_UploadInvitationToBid.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        request.setAttribute("success", "Success");
        ServletContext context = getServletContext();
        RequestDispatcher dispatch = context.getRequestDispatcher("/BAC_Home");
        dispatch.forward(request, response);

    } finally {
        out.close();
    }

}

From source file:Servlet.Contractor_UploadBiddingProposal.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//  w w  w. ja va 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();
    HttpSession session = request.getSession();

    try {

        InputStream inputStream = null;

        ArrayList<String> files = new ArrayList<String>();
        ArrayList<String> fileType = new ArrayList<String>();
        ContractorDAO contDAO = new ContractorDAO();
        OCPDDAO oc = new OCPDDAO();

        //Gets the contractor
        Contractor_User contractor_user = (Contractor_User) session.getAttribute("user");
        Contractor contractor = contractor_user.getContractor();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

                String id = null;
                String title = null;
                File path = null;

                //File path = null;
                File uploadedFiles = null;
                String fileName = null;
                String documentType = null;

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (item.isFormField()) {

                        //Returns the string inside the field
                        String value = item.getString();
                        //returns the name of the field
                        String value2 = item.getFieldName();

                        if (value2.equals("projectId")) {
                            id = value;

                        }
                        if (value2.equals("projectName")) {
                            title = value;

                        }

                    }

                    if (!item.isFormField()) {
                        fileName = item.getName();
                        String root = getServletContext().getRealPath("/");
                        //path where the file will be stored
                        path = new File("C:\\Users\\AdrianKyle\\Documents\\NetBeansProjects\\Cogito\\Upload"
                                + "/Bids and Awards Department" + "/Eligibility Documents/" + title + "/"
                                + contractor.getName());

                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        uploadedFiles = new File(path + "/" + fileName);
                        item.write(uploadedFiles);

                    }

                }

                Project project = oc.getBasicProjectDetails(id);
                Contractor_Has_Project contProject = contDAO.getContractorHasProject(project, contractor);
                contDAO.updateConHasProject(contProject.getID());

                Eligibility_Document document = new Eligibility_Document(0, fileName,
                        "chrome-extension://affgigbpilagplecbaihihkcaddmlkji/" + "Bids and Awards Department"
                                + "/Eligibility Documents/" + title + "/" + contractor.getName(),
                        null, contProject, "Bidding Proposal", null, "");
                contDAO.uploadEligibilityDocuments(document);

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                Logger.getLogger(Contractor_UploadBiddingProposal.class.getName()).log(Level.SEVERE, null, ex);
            }

        }

        request.setAttribute("success", "Success");
        ServletContext context = getServletContext();
        RequestDispatcher dispatch = context.getRequestDispatcher("/Contractor_HandleInvitations");
        dispatch.forward(request, response);

    } finally {
        out.close();
    }

}

From source file:net.lightbody.bmp.proxy.jetty.servlet.Forward.java

public void doGet(HttpServletRequest sreq, HttpServletResponse sres) throws ServletException, IOException {
    String path = (String) sreq.getAttribute("javax.servlet.include.servlet_path");
    if (path == null)
        path = sreq.getServletPath();/*from w  w w  .j  a  va2  s.c o m*/
    if (path.length() == 0) {
        path = (String) sreq.getAttribute("javax.servlet.include.path_info");
        if (path == null)
            path = sreq.getPathInfo();
    }

    String forward = (String) _forwardMap.get(path);
    if (log.isDebugEnabled())
        log.debug("Forward " + path + " to " + forward);
    if (forward != null) {
        ServletContext context = getServletContext().getContext(forward);
        String contextPath = sreq.getContextPath();
        if (contextPath.length() > 1)
            forward = forward.substring(contextPath.length());

        RequestDispatcher dispatch = context.getRequestDispatcher(forward);
        if (dispatch != null) {
            dispatch.forward(sreq, sres);
            return;
        }
    }

    sres.sendError(404);
}

From source file:com.ikon.servlet.admin.StatsGraphServlet.java

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    String action = WebUtils.getString(request, "action", "graph");
    String type = WebUtils.getString(request, "t");
    JFreeChart chart = null;//from   w  w w.  j  av  a 2  s  . com
    updateSessionManager(request);

    try {
        if ("refresh".equals(action)) {
            new RepositoryInfo().runAs(null);
            ServletContext sc = getServletContext();
            sc.getRequestDispatcher("/admin/stats.jsp").forward(request, response);
        } else {
            response.setContentType("image/png");
            OutputStream out = response.getOutputStream();

            if (DOCUMENTS.equals(type) || DOCUMENTS_SIZE.equals(type) || FOLDERS.equals(type)) {
                chart = repoStats(type);
            } else if (DISK.equals(type)) {
                chart = diskStats();
            } else if (JVM_MEMORY.equals(type)) {
                chart = jvmMemStats();
            } else if (OS_MEMORY.equals(type)) {
                chart = osMemStats();
            }

            if (chart != null) {
                // Customize title font
                chart.getTitle().setFont(new Font("Tahoma", Font.BOLD, 16));

                // Match body {   background-color:#F6F6EE; }
                chart.setBackgroundPaint(new Color(246, 246, 238));

                // Customize no data
                PiePlot plot = (PiePlot) chart.getPlot();
                plot.setNoDataMessage("No data to display");

                // Customize labels
                plot.setLabelGenerator(null);

                // Customize legend
                LegendTitle legend = new LegendTitle(plot, new ColumnArrangement(), new ColumnArrangement());
                legend.setPosition(RectangleEdge.BOTTOM);
                legend.setFrame(BlockBorder.NONE);
                legend.setItemFont(new Font("Tahoma", Font.PLAIN, 12));
                chart.removeLegend();
                chart.addLegend(legend);

                if (DISK.equals(type) || JVM_MEMORY.equals(type) || OS_MEMORY.equals(type)) {
                    ChartUtilities.writeChartAsPNG(out, chart, 225, 225);
                } else {
                    ChartUtilities.writeChartAsPNG(out, chart, 250, 250);
                }
            }

            out.flush();
            out.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:controllers.ControllerServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request//from w ww  . ja v a  2s .co 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 {

    String userPath = request.getServletPath();

    if (userPath.equals("/addWorker")) {
        String name = (String) request.getParameter("nameField");
        try {
            UFNS.getInstance().addWorkerWithName(name);
            this.save();
            String url = "workers";
            response.sendRedirect(url);
        } catch (WrongNumberValueException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    } else if (userPath.equals("/deleteWorker")) {
        String id = (String) request.getParameter("id");
        try {
            UFNS.getInstance().removeWorkerWithId(Long.parseLong(id));
            this.save();
        } catch (WrongNumberValueException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        String url = "workers";
        response.sendRedirect(url);
    } else if (userPath.equals("/deleteContract")) {
        String id = (String) request.getParameter("id");
        String contractid = (String) request.getParameter("contractId");
        try {
            Worker w = UFNS.getInstance().getWorkerWithId(Long.parseLong(id));
            w.removeContractWithId(Long.parseLong(contractid));
            this.save();
        } catch (WrongNumberValueException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        }
        String url = "contracts?id=" + id;
        response.sendRedirect(url);
    } else if (userPath.equals("/editWorker")) {
        String id = (String) request.getParameter("id");
        String name = (String) request.getParameter("name");
        String surname = (String) request.getParameter("surname");
        String lastname = (String) request.getParameter("lastname");
        try {
            Worker w = UFNS.getInstance().getWorkerWithId(Long.parseLong(id));
            w.setWorkerName(name);
            w.setWorkerSurName(surname);
            w.setWorkerLastName(lastname);
            this.save();
            ArrayList<AbstractContract> contracts;
            contracts = new ArrayList(UFNS.getInstance().getAllContractsForWorkerWithId(Long.parseLong(id)));
            ServletContext sc = getServletContext();
            RequestDispatcher rd = sc.getRequestDispatcher(userPath);

        } catch (WrongNumberValueException ex) {
            Logger.getLogger(ControllerServlet.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            String url = "contracts?id=" + id;
            response.sendRedirect(url);
        }

    } else if (userPath.equals("/addContract")) {
        String id = (String) request.getParameter("id");
        String post = (String) request.getParameter("post");
        String workplace = (String) request.getParameter("workplace");
        boolean budget = Boolean.parseBoolean(request.getParameter("budget").toString());
        try {
            Worker w = UFNS.getInstance().getWorkerWithId(Long.parseLong(id));
            if (budget) {
                w.addContract(new BudgetContract(workplace, post));
            } else {
                w.addContract(new FinanceContract(workplace, post));
            }

        } catch (WrongNumberValueException ex) {

        } finally {
            String url = "contracts?id=" + id;
            response.sendRedirect(url);
        }
    }

}

From source file:Servlet.Contractor_ReUpload.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();
    HttpSession session = request.getSession();

    try {

        InputStream inputStream = null;

        ArrayList<String> files = new ArrayList<String>();
        ArrayList<String> fileType = new ArrayList<String>();
        ContractorDAO contDAO = new ContractorDAO();
        OCPDDAO oc = new OCPDDAO();

        //Gets the contractor
        Contractor_User contractor_user = (Contractor_User) session.getAttribute("user");
        Contractor contractor = contractor_user.getContractor();

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if (isMultipart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);

            try {

                List items = upload.parseRequest(request);
                Iterator iterator = items.iterator();

                String id = null;
                int docID = 0;
                String title = null;
                File path = null;

                //File path = null;
                File uploadedFiles = null;
                String fileName = null;
                String documentType = null;

                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if (item.isFormField()) {

                        //Returns the string inside the field
                        String value = item.getString();
                        //returns the name of the field
                        String value2 = item.getFieldName();

                        if (value2.equals("docID")) {
                            docID = Integer.parseInt(value);

                        }
                        if (value2.equals("doctype1")) {
                            documentType = value;

                        }
                        if (value2.equals("ProjectID")) {
                            id = value;

                        }
                        if (value2.equals("ProjectName")) {
                            title = value;

                        }

                    }

                    if (!item.isFormField()) {
                        fileName = item.getName();

                        String root = getServletContext().getRealPath("/");
                        //path where the file will be stored
                        path = new File("C:\\Users\\AdrianKyle\\Documents\\NetBeansProjects\\Cogito\\Upload"
                                + "/Bids and Awards Department" + "/Eligibility Documents/" + title + "/"
                                + contractor.getName());

                        if (!path.exists()) {
                            boolean status = path.mkdirs();
                        }

                        uploadedFiles = new File(path + "/" + fileName);
                        item.write(uploadedFiles);

                    }

                }

                Project project = oc.getBasicProjectDetails(id);
                Contractor_Has_Project contProject = contDAO.getContractorHasProject(project, contractor);

                Eligibility_Document document = new Eligibility_Document(0, fileName,
                        "chrome-extension://affgigbpilagplecbaihihkcaddmlkji/" + "Bids and Awards Department"
                                + "/Eligibility Documents/" + title + "/" + contractor.getName(),
                        null, contProject, documentType, null, "");
                contDAO.updateEligibilityDocument(docID, document);

            } catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception ex) {
                Logger.getLogger(Contractor_UploadContractorDocuments.class.getName()).log(Level.SEVERE, null,
                        ex);
            }

        }

        request.setAttribute("success", "Success");
        ServletContext context = getServletContext();
        RequestDispatcher dispatch = context.getRequestDispatcher("/Contractor_HandleInvitations");
        dispatch.forward(request, response);

    } finally {
        out.close();
    }

}

From source file:org.docx4j.template.jsp.engine.JspTemplateImpl.java

private void doInterpret(String requestURL, Map<String, Object> variables, OutputStream output)
        throws IOException, ServletException {
    /**//from  www . j av a  2s  .  c  om
      * ServletContext?RequestDispatcher
      */
    ServletContext sc = request.getSession().getServletContext();
    /**
     * ???reqeustDispatcher
     */
    RequestDispatcher rd = sc.getRequestDispatcher(requestURL);
    /**
     * ByteArrayOutputStream?,??
     */
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();

    /**
     * ServletOutputStreamwrite
     */
    final ServletOutputStream outputStream = new ServletOutputStream() {

        public void write(int b) throws IOException {
            /**
             * ?
             */
            baos.write(b);
        }

        @SuppressWarnings("unused")
        public boolean isReady() {
            return false;
        }

    };
    /**
     *  OutputStream  PrintWriter
     * OutputStreamWriter ????? charset ????
     */
    final PrintWriter pw = new PrintWriter(new OutputStreamWriter(baos, config.getOutputEncoding()), true);
    /**
     * ?HttpServletResponse??response
     */
    HttpServletResponse resp = new HttpServletResponseWrapper(response) {
        /**
         * getOutputStream(ServletResponse)ServletOutputStream
         * ?response
         * ?byteArrayOutputStream
         */
        public ServletOutputStream getOutputStream() {
            return outputStream;
        }

        /**
         * ?getWriter(ServletResponse)PrintWriter
         * ???
         */
        public PrintWriter getWriter() {
            return pw;
        }
    };
    /**
     * ?jsp RequestDispatcher.include(ServletRequest request,
     * ServletResponse response) RequestDispatcher??response
     */
    rd.include(request, resp);
    pw.flush();
    /**
     * ByteArrayOutputStreamwriteTo?????ByteArray
     */
    baos.writeTo(output);
}

From source file:com.ikon.servlet.admin.ReportServlet.java

/**
 * List registered reports//  ww  w. j a v  a2s . co  m
 */
private void list(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException {
    log.debug("list({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    List<Report> list = ReportDAO.findAll();
    sc.setAttribute("reports", list);
    sc.getRequestDispatcher("/admin/report_list.jsp").forward(request, response);
    log.debug("list: void");
}