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:at.gv.egovernment.moa.id.auth.servlet.AuthServlet.java

protected void handleErrorNoRedirect(String errorMessage, Throwable exceptionThrown, HttpServletRequest req,
        HttpServletResponse resp) {/*from  ww  w.  jav a2 s  .co m*/

    if (null != errorMessage) {
        Logger.error(errorMessage);
        req.setAttribute("ErrorMessage", errorMessage);
    }

    if (null != exceptionThrown) {
        if (null == errorMessage)
            errorMessage = exceptionThrown.getMessage();
        Logger.error(errorMessage, exceptionThrown);
        req.setAttribute("ExceptionThrown", exceptionThrown);
    }

    if (Logger.isDebugEnabled()) {
        req.setAttribute("LogLevel", "debug");
    }

    StatisticLogger logger = StatisticLogger.getInstance();
    logger.logErrorOperation(exceptionThrown);

    // forward this to errorpage-auth.jsp where the HTML error page is
    // generated
    ServletContext context = getServletContext();
    RequestDispatcher dispatcher = context.getRequestDispatcher("/errorpage-auth.jsp");
    try {

        resp.setHeader(MOAIDAuthConstants.HEADER_EXPIRES, MOAIDAuthConstants.HEADER_VALUE_EXPIRES);
        resp.setHeader(MOAIDAuthConstants.HEADER_PRAGMA, MOAIDAuthConstants.HEADER_VALUE_PRAGMA);
        resp.setHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL, MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL);
        resp.addHeader(MOAIDAuthConstants.HEADER_CACHE_CONTROL,
                MOAIDAuthConstants.HEADER_VALUE_CACHE_CONTROL_IE);

        dispatcher.forward(req, resp);
    } catch (ServletException e) {
        Logger.error(e);
    } catch (IOException e) {
        Logger.error(e);
    }
}

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

/**
 * List omr templates/*from   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<Omr> list = OmrDAO.getInstance().findAll();
    sc.setAttribute("omr", list);
    sc.getRequestDispatcher("/admin/omr_list.jsp").forward(request, response);
    log.debug("list: void");
}

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

public void doGet(HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    log.debug("doGet({}, {})", request, response);
    request.setCharacterEncoding("UTF-8");
    String action = WebUtils.getString(request, "action");
    String userId = request.getRemoteUser();
    updateSessionManager(request);//from  w  ww.j ava2s  . c o  m

    try {
        if (action.equals("create")) {
            ServletContext sc = getServletContext();
            Report rp = new Report();
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("edit")) {
            ServletContext sc = getServletContext();
            int rpId = WebUtils.getInt(request, "rp_id");
            Report rp = ReportDAO.findByPk(rpId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("delete")) {
            ServletContext sc = getServletContext();
            int rpId = WebUtils.getInt(request, "rp_id");
            Report rp = ReportDAO.findByPk(rpId);
            sc.setAttribute("action", action);
            sc.setAttribute("types", types);
            sc.setAttribute("rp", rp);
            sc.getRequestDispatcher("/admin/report_edit.jsp").forward(request, response);
        } else if (action.equals("paramList")) {
            paramList(userId, request, response);
        } else if (action.equals("getParams")) {
            getParams(userId, request, response);
        } else if (action.equals("execute")) {
            execute(userId, request, response);
        } else {
            list(userId, request, response);
        }
    } catch (DatabaseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (JRException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (EvalError e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (ParseException e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    } catch (Exception e) {
        log.error(e.getMessage(), e);
        sendErrorRedirect(request, response, e);
    }
}

From source file:Servlet.Citizen_SendTestimonial.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//from  w  ww  .ja v  a2 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 {
        ActivityDAO actdao = new ActivityDAO();

        CitizenDAO citizenDAO = new CitizenDAO();
        InputStream inputStream = null;
        Citizen c = (Citizen) session.getAttribute("user");
        ArrayList<String> files = new ArrayList<String>();

        String category = null;

        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 title = null;
                String message = null;
                String location = null;
                String videoD = null;
                String imageD = null;
                String documentD = 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("testimonialtitle")) {
                            title = value;
                        }
                        if (value2.equals("testimonialtype")) {
                            category = value;
                        }
                        if (value2.equals("testimonialdescription")) {
                            message = value;
                        }
                        if (value2.equals("hiddenlocation")) {
                            location = value;
                        }
                        if (value2.equals("videodescription")) {
                            videoD = value;
                        }
                        if (value2.equals("imagedescription")) {
                            imageD = value;
                        }
                        if (value2.equals("documentdescription")) {
                            documentD = value;
                        }
                    }

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

                            //path where the file will be stored
                            path = new File("C:\\Users\\AdrianKyle\\Documents\\NetBeansProjects\\Cogito\\Upload"
                                    + "/Citizen/" + title);
                            if (!path.exists()) {
                                boolean status = path.mkdirs();
                            }

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

                        }
                    }
                }

                //For testimonial category
                //                    for (int x = 0; x < files.size(); x++) {
                //
                //                        String filename = files.get(x);
                //                        if (!filename.isEmpty()) {
                //                            String[] parts = filename.split(Pattern.quote("."));
                //                            String extension = parts[1];
                //                            //Videos
                //                            if (extension.equalsIgnoreCase("mp4") || extension.equalsIgnoreCase("avi") || extension.equalsIgnoreCase("3gp") || extension.equalsIgnoreCase("flv") || extension.equalsIgnoreCase("wmv")) {
                //                                category = "video";
                //                                break;
                //                            } //Images
                //                            else if (extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("bmp")) {
                //                                category = "image";
                //                                break;
                //                            }
                //                        }
                //                    }
                Testimonial t = new Testimonial(title, null, message,
                        "chrome-extension://affgigbpilagplecbaihihkcaddmlkji/Citizen/", category, "Pending", c);
                //Upload testimonial
                citizenDAO.submitTestimonial(t);
                t.setId(citizenDAO.lastID());

                //Add activity
                actdao.addActivity(new Activity(0, "you have submitted a testimonial entitled " + title, null,
                        c.getUser()));

                //set location
                String[] loc = location.split(",");
                ArrayList<TLocation> tLoc = new ArrayList<>();
                ArrayList<String> longitude = new ArrayList<>();
                ArrayList<String> latitude = new ArrayList<>();

                for (int x = 0; x < loc.length; x++) {
                    String[] latlong = loc[x].split("&");
                    String thislat = latlong[0];
                    String thislong = latlong[1];
                    longitude.add(thislong);
                    latitude.add(thislat);
                }

                for (int x = 0; x < loc.length; x++) {
                    TLocation l = new TLocation();
                    l.setLongitude(longitude.get(x));
                    l.setLatitude(latitude.get(x));
                    l.setTestimonial(t);
                    tLoc.add(l);
                }

                for (TLocation tl : tLoc) {
                    citizenDAO.setLocation(tl);
                }
                //Place in appropriate tables
                for (int x = 0; x < files.size(); x++) {

                    String filename = files.get(x);
                    if (!filename.isEmpty()) {

                        String[] parts = filename.split(Pattern.quote("."));
                        String extension = parts[1];
                        //Videos
                        if (extension.equalsIgnoreCase("mp4") || extension.equalsIgnoreCase("avi")
                                || extension.equalsIgnoreCase("3gp") || extension.equalsIgnoreCase("flv")
                                || extension.equalsIgnoreCase("wmv") || extension.equalsIgnoreCase("mkv")) {
                            Files f = new Files();
                            f.setFileName(files.get(x));
                            f.setType("Video");
                            f.setTestimonial(t);
                            f.setStatus("Approved");
                            f.setDescription(videoD);
                            f.setUploader(c.getUser().getUsername());
                            citizenDAO.submitFiles(f);

                        } //Images
                        else if (extension.equalsIgnoreCase("png") || extension.equalsIgnoreCase("jpeg")
                                || extension.equalsIgnoreCase("jpg") || extension.equalsIgnoreCase("bmp")) {
                            Files f = new Files();
                            f.setFileName(files.get(x));
                            f.setType("Image");
                            f.setTestimonial(t);
                            f.setStatus("Approved");
                            f.setDescription(imageD);
                            f.setUploader(c.getUser().getUsername());
                            citizenDAO.submitFiles(f);
                        } //Documents 
                        else if (extension.equalsIgnoreCase("pdf") || extension.equalsIgnoreCase("docx")
                                || extension.equalsIgnoreCase("doc") || extension.equalsIgnoreCase("pptx")
                                || extension.equalsIgnoreCase("txt") || extension.equalsIgnoreCase("xlsx")) {
                            Files f = new Files();
                            f.setFileName(files.get(x));
                            f.setType("Document");
                            f.setTestimonial(t);
                            f.setStatus("Approved");
                            f.setDescription(documentD);
                            f.setUploader(c.getUser().getUsername());
                            citizenDAO.submitFiles(f);
                        }

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

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

    } finally {
        out.close();
    }
}

From source file:Servlet.Contractor_UploadContractorDocuments.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*from w  w  w  . j av  a 2 s  .c om*/
 *
 * @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);
                        files.add(fileName);

                        String fieldname = item.getFieldName();
                        //Add the conditions here
                        if (fieldname.equalsIgnoreCase("SEC / DTI / CDA registration")) {

                            documentType = "SEC / DTI / CDA registration";

                        } else if (fieldname.equalsIgnoreCase("Mayor's permit")) {

                            documentType = "Mayor's permit";

                        } else if (fieldname
                                .equalsIgnoreCase("On-going / Completed government and private contracts")) {

                            documentType = "On-going / Completed government and private contracts";

                        } else if (fieldname.equalsIgnoreCase("Income Tax Return (ITR)")) {

                            documentType = "Income Tax Return (ITR)";

                        } else if (fieldname.equalsIgnoreCase("Net financial contracting capacity")) {

                            documentType = "Net financial contracting capacity";

                        } else if (fieldname.equalsIgnoreCase(
                                "Cash, Cashier's / Manager's Check, Bank Draft / Guarantee")) {

                            documentType = "Cash, Cashier's / Manager's Check, Bank Draft / Guarantee";

                        } else if (fieldname.equalsIgnoreCase("Letter of credit")) {

                            documentType = "Letter of credit";

                        } else if (fieldname.equalsIgnoreCase("Surety bond")) {

                            documentType = "Surety bond";

                        } else if (fieldname.equalsIgnoreCase("Bid Security")) {

                            documentType = "Bid Security";

                        } else if (fieldname.equalsIgnoreCase("Authority of the signing official")) {

                            documentType = "Authority of the signing official";

                        } else if (fieldname.equalsIgnoreCase("Construction Schedule")) {

                            documentType = "Construction Schedule";

                        } else if (fieldname.equalsIgnoreCase("Manpower Schedule")) {

                            documentType = "Manpower Schedule";

                        } else if (fieldname.equalsIgnoreCase("Construction Methods")) {

                            documentType = "Construction Methods";

                        } else if (fieldname.equalsIgnoreCase("Organizational Chart")) {

                            documentType = "Organizational Chart";

                        } else if (fieldname.equalsIgnoreCase("Contractor Personnel list")) {

                            documentType = "Contractor Personnel list";

                        } else if (fieldname.equalsIgnoreCase("List of equipment owned")) {

                            documentType = "List of equipment owned";

                        } else if (fieldname.equalsIgnoreCase("Equipment Utilization Schedule")) {

                            documentType = "Equipment Utilization Schedule";

                        } else if (fieldname.equalsIgnoreCase("Affidavit of site Inspection")) {

                            documentType = "Affidavit of site Inspection";

                        } else if (fieldname.equalsIgnoreCase("Certificate of Non Blacklisted")) {

                            documentType = "Certificate of Non Blacklisted";

                        } else if (fieldname.equalsIgnoreCase("Construction Safety and Health Program")) {

                            documentType = "Construction Safety and Health Program";

                        } else if (fieldname.equalsIgnoreCase(
                                "Certificate of compliance with existing labor laws and standard")) {

                            documentType = "Certificate of compliance with existing labor laws and standard";

                        } else if (fieldname.equalsIgnoreCase("Omnibus Sworn")) {

                            documentType = "Omnibus Sworn";

                        }

                        fileType.add(documentType);

                    }

                }

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

                for (int x = 0; x < files.size(); x++) {
                    Eligibility_Document document = new Eligibility_Document(0, files.get(x),
                            "chrome-extension://affgigbpilagplecbaihihkcaddmlkji/"
                                    + "Bids and Awards Department" + "/Eligibility Documents/" + title + "/"
                                    + contractor.getName(),
                            null, contProject, fileType.get(x), null, "");
                    contDAO.uploadEligibilityDocuments(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:password.pwm.http.PwmResponse.java

public void forwardToJsp(final JspUrl jspURL) throws ServletException, IOException, PwmUnrecoverableException {
    if (!pwmRequest.isFlag(PwmRequestFlag.NO_REQ_COUNTER)) {
        pwmRequest.getPwmSession().getSessionManager().incrementRequestCounterKey();
    }/*from w ww  .j av a  2s  .c o  m*/

    preCommitActions();

    final HttpServletRequest httpServletRequest = pwmRequest.getHttpServletRequest();
    final ServletContext servletContext = httpServletRequest.getSession().getServletContext();
    final String url = jspURL.getPath();
    try {
        LOGGER.trace(pwmRequest.getSessionLabel(), "forwarding to " + url);
    } catch (Exception e) {
        /* noop, server may not be up enough to do the log output */
    }
    servletContext.getRequestDispatcher(url).forward(httpServletRequest, this.getHttpServletResponse());
}

From source file:org.apache.catalina.core.StandardHostValve.java

/**
 * Handle an HTTP status code or Java exception by forwarding control
 * to the location included in the specified errorPage object.  It is
 * assumed that the caller has already recorded any request attributes
 * that are to be forwarded to this page.  Return <code>true</code> if
 * we successfully utilized the specified error page location, or
 * <code>false</code> if the default error report should be rendered.
 *
 * @param request The request being processed
 * @param response The response being generated
 * @param errorPage The errorPage directive we are obeying
 *//*from   www. j a v a 2s.  c o m*/
protected boolean custom(Request request, Response response, ErrorPage errorPage) {

    if (debug >= 1)
        log("Processing " + errorPage);

    // Validate our current environment
    if (!(request instanceof HttpRequest)) {
        if (debug >= 1)
            log(" Not processing an HTTP request --> default handling");
        return (false); // NOTE - Nothing we can do generically
    }
    HttpServletRequest hreq = (HttpServletRequest) request.getRequest();
    if (!(response instanceof HttpResponse)) {
        if (debug >= 1)
            log("Not processing an HTTP response --> default handling");
        return (false); // NOTE - Nothing we can do generically
    }
    HttpServletResponse hres = (HttpServletResponse) response.getResponse();

    ((HttpRequest) request).setPathInfo(errorPage.getLocation());

    try {

        // Reset the response if possible (else IllegalStateException)
        //hres.reset();
        // Reset the response (keeping the real error code and message)
        Integer statusCodeObj = (Integer) hreq.getAttribute(Globals.STATUS_CODE_ATTR);
        int statusCode = statusCodeObj.intValue();
        String message = (String) hreq.getAttribute(Globals.ERROR_MESSAGE_ATTR);
        ((HttpResponse) response).reset(statusCode, message);

        // Forward control to the specified location
        ServletContext servletContext = request.getContext().getServletContext();
        RequestDispatcher rd = servletContext.getRequestDispatcher(errorPage.getLocation());
        rd.forward(hreq, hres);

        // If we forward, the response is suspended again
        response.setSuspended(false);

        // Indicate that we have successfully processed this custom page
        return (true);

    } catch (Throwable t) {

        // Report our failure to process this custom page
        log("Exception Processing " + errorPage, t);
        return (false);

    }

}

From source file:com.emc.plants.web.servlets.ShoppingServlet.java

/**
 * Request dispatch/*w ww . j  a  va  2  s .co  m*/
 */
private void requestDispatch(ServletContext ctx, HttpServletRequest req, HttpServletResponse resp, String page)
        throws ServletException, IOException {
    resp.setContentType("text/html");
    ctx.getRequestDispatcher("/" + page).forward(req, resp);
}

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

/**
 * Show report parameters, previous step to execution
 *///from w  w  w.  j  av  a 2 s.com
private void getParams(String userId, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException, ParseException {
    log.debug("getParams({}, {}, {})", new Object[] { userId, request, response });
    ServletContext sc = getServletContext();
    int rpId = WebUtils.getInt(request, "rp_id");
    List<FormElement> params = ReportUtils.getReportParameters(rpId);

    sc.setAttribute("rp_id", rpId);
    sc.setAttribute("params", params);
    sc.setAttribute("ReportUtil", new ReportUtils());
    sc.getRequestDispatcher("/admin/report_get_params.jsp").forward(request, response);
    log.debug("getParams: void");
}

From source file:com.openkm.servlet.admin.StampServlet.java

/**
 * List text stamp//w w  w. ja v  a2 s  . c  o m
 */
private void textList(Session session, HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, DatabaseException, PrincipalAdapterException {
    log.debug("textList({}, {}, {})", new Object[] { session, request, response });
    ServletContext sc = getServletContext();
    sc.setAttribute("stamps", StampTextDAO.findAll());
    sc.getRequestDispatcher("/admin/stamp_text_list.jsp").forward(request, response);
    log.debug("textList: void");
}