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:es.uma.inftel.blog.servlet.RegistroServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request//from   ww  w  .j a v a  2s . c  o  m
 * @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 {

    request.setCharacterEncoding("UTF-8");

    String username = request.getParameter("username");
    String password = request.getParameter("password");

    RegistroViewFacade registroViewFacade = new RegistroViewFacade(postFacade);

    RequestDispatcher registroRequestDispatcher = request.getRequestDispatcher("registro.jsp");
    if (username == null && password == null) {
        request.setAttribute("registroView", registroViewFacade.createView(false));
        registroRequestDispatcher.forward(request, response);
        return;
    }

    String email = request.getParameter("email");

    Part filePart = request.getPart("avatar");
    InputStream inputStream = filePart.getInputStream();
    byte[] avatar = IOUtils.toByteArray(inputStream);

    Usuario usuario = registrarUsuario(username, password, email, avatar);
    if (usuario == null) {
        request.setAttribute("registroView", registroViewFacade.createView(true));
        registroRequestDispatcher.forward(request, response);
    } else {
        HttpSession session = request.getSession();
        session.setAttribute("usuario", usuario);
        response.sendRedirect("index");
    }
}

From source file:cheladocs.controlo.DocumentoServlet.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    response.setContentType("application/pdf; application/msword; application/excel");

    String comando = request.getParameter("comando");

    if (comando == null) {
        comando = "principal";
    }/*from   ww w  .  ja  va  2s  .co  m*/

    DocumentoDAO documentoDAO;
    Documento documento = new Documento();

    if (comando == null || !comando.equalsIgnoreCase("principal")) {
        try {
            idDocumento = request.getParameter("numero_protocolo");
            if (idDocumento != null) {
                documento.setNumeroProtocolo(Integer.parseInt(idDocumento));
            }

        } catch (NumberFormatException ex) {
            System.err.println("Erro ao converter dado: " + ex.getMessage());
        }
    }

    try {

        documentoDAO = new DocumentoDAO();

        if (comando.equalsIgnoreCase("guardar")) {

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }
            documentoDAO.save(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("editar")) {

            documento.setNumeroProtocolo(Integer.parseInt(request.getParameter("requerente")));

            documento.getRequerente().setIdRequerente(Integer.parseInt(request.getParameter("requerente")));
            documento.setDataEntrada(Date.valueOf(request.getParameter("data_entrada")));
            documento.setOrigem(request.getParameter("origem_documento"));
            documento.setDescricaoAssunto(request.getParameter("descricao_assunto"));
            documento.getNaturezaAssunto()
                    .setIdNaturezaAssunto(Integer.parseInt(request.getParameter("natureza_assunto")));
            documento.getTipoExpediente()
                    .setIdTipoExpediente(Integer.parseInt(request.getParameter("tipo_expediente")));
            Part ficheiro = request.getPart("ficheiro");
            if (ficheiro != null) {
                byte[] ficheiroDados = IOUtils.toByteArray(ficheiro.getInputStream());
                documento.setConteudoDocumento(ficheiroDados);
                documento.setUrlFicheiroDocumento(ficheiro.getSubmittedFileName());
                doUpload(ficheiro, request);
            }

            documentoDAO.update(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("eliminar")) {
            documentoDAO.delete(documento);
            response.sendRedirect("paginas/gerir_documento.jsp");

        } else if (comando.equalsIgnoreCase("prepara_editar")) {
            documento = documentoDAO.findById(documento.getNumeroProtocolo());
            request.setAttribute("documento", documento);

            RequestDispatcher rd = request.getRequestDispatcher("paginas/documento_editar.jsp");
            rd.forward(request, response);
        } else if (comando.equalsIgnoreCase("listar")) {

            response.sendRedirect("paginas/gerir_documento.jsp");
        } else if (comando.equalsIgnoreCase("imprimir_todos") || comando.equalsIgnoreCase("imprimir_by_id")) {
            ReporteUtil reporte = new ReporteUtil();
            File caminhoRelatorio = null;
            HashMap hashMap = new HashMap();

            if (comando.equalsIgnoreCase("imprimir_todos")) {
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/DocumentoListar.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            } else {
                hashMap.put("codigo_documento", Integer.parseInt(idDocumento));
                caminhoRelatorio = new File(getServletConfig().getServletContext()
                        .getRealPath("/WEB-INF/relatorios/Ficha_Documento.jasper"));
                reporte.geraRelatorio(caminhoRelatorio.getPath(), hashMap, response);
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

From source file:edu.morgan.server.UploadFile.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    RequestDispatcher rd;
    response.setContentType("text/html");

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        rd = request.getRequestDispatcher("fail.jsp");
        rd.forward(request, response);
    }//from w  ww .ja v a  2  s  .  c  om

    try {
        ServletFileUpload upload = new ServletFileUpload();
        response.setContentType("text/plain");

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            this.read(stream);
        }
        request.removeAttribute("incompleteStudents");
        request.setAttribute("incompleteStudents", studentList);

        rd = request.getRequestDispatcher("Success");
        rd.forward(request, response);

    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:com.globalsight.everest.webapp.pagehandler.projects.workflows.JobControlCompletedHandler.java

/**
 * Invokes this EntryPageHandler object// w  w  w . j  a  va  2 s.co m
 * <p>
 * @param p_ageDescriptor the description of the page to be produced.
 * @param p_request original request sent from the browser.
 * @param p_response original response object.
 * @param p_context the Servlet context.
 */
public void myInvokePageHandler(WebPageDescriptor p_thePageDescriptor, HttpServletRequest p_request,
        HttpServletResponse p_response, ServletContext p_context)
        throws ServletException, IOException, RemoteException, EnvoyServletException {
    HttpSession session = p_request.getSession(false);
    SessionManager sessionMgr = (SessionManager) session.getAttribute(SESSION_MANAGER);

    if (p_request.getParameter("action") != null
            && "checkDownloadQAReport".equals(p_request.getParameter("action"))) {
        ServletOutputStream out = p_response.getOutputStream();
        String jobIds = p_request.getParameter("jobIds");
        boolean checkQA = checkQAReport(sessionMgr, jobIds);
        String download = "";
        if (checkQA) {
            download = "success";
        } else {
            download = "fail";
        }
        Map<String, Object> returnValue = new HashMap();
        returnValue.put("download", download);
        out.write((JsonUtil.toObjectJson(returnValue)).getBytes("UTF-8"));
        return;
    } else if (p_request.getParameter("action") != null
            && "downloadQAReport".equals(p_request.getParameter("action"))) {
        Set<Long> jobIdSet = (Set<Long>) sessionMgr.getAttribute("jobIdSet");
        Set<File> exportFilesSet = (Set<File>) sessionMgr.getAttribute("exportFilesSet");
        Set<String> localesSet = (Set<String>) sessionMgr.getAttribute("localesSet");
        long companyId = (Long) sessionMgr.getAttribute("companyId");
        WorkflowHandlerHelper.zippedFolder(p_request, p_response, companyId, jobIdSet, exportFilesSet,
                localesSet);
        sessionMgr.removeElement("jobIdSet");
        sessionMgr.removeElement("exportFilesSet");
        sessionMgr.removeElement("localesSet");
        return;
    }

    boolean stateMarch = false;
    if (Job.LOCALIZED.equals((String) sessionMgr.getMyjobsAttribute("lastState")))
        stateMarch = true;
    setJobSearchFilters(sessionMgr, p_request, stateMarch);

    m_exportBean = new NavigationBean(EXPORT_BEAN, p_thePageDescriptor.getPageName());
    HashMap beanMap = invokeJobControlPage(p_thePageDescriptor, p_request, LOCALIZED_BEAN);
    p_request.setAttribute("searchType", p_request.getParameter("searchType"));
    p_request.setAttribute("action", p_request.getParameter("action"));
    performAppropriateOperation(p_request);

    sessionMgr.setMyjobsAttribute("lastState", Job.LOCALIZED);
    JobVoLocalizedSearcher searcher = new JobVoLocalizedSearcher();
    searcher.setJobVos(p_request);

    p_request.setAttribute(EXPORT_URL_PARAM, m_exportBean.getPageURL());
    p_request.setAttribute(JOB_ID, JOB_ID);
    p_request.setAttribute(JOB_LIST_START_PARAM, p_request.getParameter(JOB_LIST_START_PARAM));
    p_request.setAttribute(PAGING_SCRIPTLET,
            getPagingText(p_request, ((NavigationBean) beanMap.get(BASE_BEAN)).getPageURL(), Job.LOCALIZED));
    // Set the EXPORT_INIT_PARAM in the sessionMgr so we can bring
    // the user back here after they Export
    sessionMgr.setAttribute(JobManagementHandler.EXPORT_INIT_PARAM, BASE_BEAN);

    sessionMgr.setAttribute("destinationPage", "localized");
    //clear the session for download job from joblist page
    sessionMgr.setAttribute(DownloadFileHandler.DOWNLOAD_JOB_LOCALES, null);
    sessionMgr.setAttribute(DownloadFileHandler.DESKTOP_FOLDER, null);
    setJobProjectsLocales(sessionMgr, session);

    // turn on cache.  do both.  "pragma" for the older browsers.
    p_response.setHeader("Pragma", "yes-cache"); //HTTP 1.0
    p_response.setHeader("Cache-Control", "yes-cache"); //HTTP 1.1
    p_response.addHeader("Cache-Control", "yes-store"); // tell proxy not to cache
    try {
        Company company = ServerProxy.getJobHandler()
                .getCompanyById(CompanyWrapper.getCurrentCompanyIdAsLong());
        p_request.setAttribute("company", company);
    } catch (Exception e) {
        e.printStackTrace();
    }
    // forward to the jsp page.
    RequestDispatcher dispatcher = p_context.getRequestDispatcher(p_thePageDescriptor.getJspURL());
    dispatcher.forward(p_request, p_response);
}

From source file:com.mockey.ui.ServiceSetupServlet.java

/**
 * //from  w  w  w.j a  va2 s.  c om
 * 
 * @param req
 *            basic request
 * @param resp
 *            basic resp
 * @throws ServletException
 *             basic
 * @throws IOException
 *             basic
 */
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    Long serviceId = null;
    try {
        serviceId = new Long(req.getParameter("serviceId"));
    } catch (Exception e) {
        // Do nothing
    }
    Service service = null;

    if (serviceId != null) {
        service = store.getServiceById(serviceId);
    }
    if (service == null) {
        service = new Service();
    }

    req.setAttribute("mockservice", service);

    req.setAttribute("requestInspectorList", PluginStore.getInstance().getRequestInspectorImplClassList());
    RequestDispatcher dispatch = req.getRequestDispatcher("/service_setup.jsp");
    dispatch.forward(req, resp);
}

From source file:edu.morgan.server.UploadFileServlet.java

@Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException {
    // Check that we have a file upload request
    RequestDispatcher rd;
    response.setContentType("text/html");

    isMultipart = ServletFileUpload.isMultipartContent(request);
    if (!isMultipart) {
        rd = request.getRequestDispatcher("fail.jsp");
        rd.forward(request, response);
    }/*from  w  ww .  j a  va  2s  .co m*/

    try {
        ServletFileUpload upload = new ServletFileUpload();
        response.setContentType("text/plain");

        FileItemIterator iterator = upload.getItemIterator(request);
        while (iterator.hasNext()) {
            FileItemStream item = iterator.next();
            InputStream stream = item.openStream();
            this.read(stream);
        }

        rd = request.getRequestDispatcher("success.jsp");
        rd.forward(request, response);

    } catch (Exception ex) {
        throw new ServletException(ex);
    }

}

From source file:mashups.eventpub.EventPublisherServlet.java

/**
 * Default action - output intro page /*  ww w. j av  a 2 s .com*/
 *
 * @param request The request 
 * @param response The response 
 */
private void processOutputIntroPage(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String ssAuthUrl = EventPublisher.getSsAuthSubUrl(getCurrentUrl(request) + "?action=acceptAuthSubToken");
    request.setAttribute("ssAuthUrl", ssAuthUrl);
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/outputIntroPage.jsp");
    dispatcher.forward(request, response);
}

From source file:controller.addGame.java

protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {

        boolean isMultiPart = ServletFileUpload.isMultipartContent(request);
        if (isMultiPart) {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            List items = upload.parseRequest(request);
            Iterator<FileItem> iter = items.iterator();
            while (iter.hasNext()) {
                FileItem fileItem = iter.next();
                if (fileItem.isFormField()) {
                    processFormField(fileItem);
                } else {
                    flItem = fileItem;//from   w  ww.  ja  v a  2 s.co m
                }
            }
        }

        Connect obj_con = new Connect();
        Connection con = obj_con.Open();

        String sql = "insert into Application_Names values(?,?,?)";
        String sql1 = "insert into required_Minimum values(?,?,?,?,?,?)";
        String sql2 = "insert into required_Recomended values(?,?,?,?,?,?)";

        PreparedStatement pr = con.prepareStatement(sql);
        PreparedStatement pr1 = con.prepareStatement(sql1);
        PreparedStatement pr2 = con.prepareStatement(sql2);

        pr.setString(1, AppName);
        pr.setString(2, Code);
        pr.setString(3, Code);

        pr1.setString(1, Code);
        pr1.setString(2, MinGpu);
        pr1.setInt(3, MinGpuLvl);
        pr1.setString(4, MinCpu);
        pr1.setInt(5, RecCpuLvl);
        pr1.setInt(6, MinRam);

        pr2.setString(1, Code);
        pr2.setString(2, RecGpu);
        pr2.setInt(3, RecGpuLvl);
        pr2.setString(4, RecCpu);
        pr2.setInt(5, RecCpuLvl);
        pr2.setInt(6, RecRam);

        int a = pr.executeUpdate();
        int b = pr1.executeUpdate();
        int c = pr2.executeUpdate();

        if (a > 0 && b > 0 && c > 0) {
            RequestDispatcher rd = request.getRequestDispatcher("viewGames.jsp");
            request.setAttribute("return", "Added Item Succesfully.");
            rd.forward(request, response);

            pr.close();
            pr1.close();
            pr2.close();
            con.close();
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("addGame.jsp");
            request.setAttribute("return", "Added Item Succesfully.");
            rd.forward(request, response);
        }

    } catch (Exception e) {
        System.out.println(e.getCause());
    }
}

From source file:mashups.eventpub.EventPublisherServlet.java

/**
 * Output list of spreadsheets owned by authenticated account 
 *
 * @param request The request /*  ww  w  . j  a  v  a 2  s  .  c o m*/
 * @param response The response 
 */
private void processOutputSsList(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EventPublisher ep = new EventPublisher();
    try {
        ep.setSsAuthSubToken((String) request.getSession().getAttribute(SESSION_ATTR_SS_AUTH_TOKEN), false);
        request.setAttribute("ssList", ep.getSsList());
    } catch (EPAuthenticationException e) {
        System.err.println("Authentication exception: " + e.getMessage());
    }
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/outputSsList.jsp");
    dispatcher.forward(request, response);
}

From source file:mashups.eventpub.EventPublisherServlet.java

/**
 * Output list of worksheets in chosen spreadsheet 
 *
 * @param request The request /*from   w w w.  jav  a  2 s  .  com*/
 * @param response The response 
 */
private void processOutputWsList(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    EventPublisher ep = new EventPublisher();
    try {
        ep.setSsAuthSubToken((String) request.getSession().getAttribute(SESSION_ATTR_SS_AUTH_TOKEN), false);
        request.setAttribute("token", ep.getSsAuthSubToken());
        request.setAttribute("wsList", ep.getWsList((String) request.getParameter("wsFeed")));
    } catch (EPAuthenticationException e) {
        System.err.println("Authentication exception: " + e.getMessage());
    }

    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/WEB-INF/jsp/outputWsList.jsp");
    dispatcher.forward(request, response);
}