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:org.pentaho.di.baserver.utils.web.HttpConnectionHelper.java

protected Response invokePlatformEndpoint(final String endpointPath, final String httpMethod,
        final Map<String, String> queryParameters) {

    Response response = new Response();

    // get servlet context and request dispatcher
    ServletContext servletContext = null;
    RequestDispatcher requestDispatcher = null;
    try {/*  w ww. j  a  v a  2 s. c  o  m*/
        Object context = getContext();
        if (context instanceof ServletContext) {
            servletContext = (ServletContext) context;
            requestDispatcher = servletContext.getRequestDispatcher("/api" + endpointPath);
        }
    } catch (NoClassDefFoundError ex) {
        logger.error("Failed to get application servlet context", ex);
        return response;
    }

    if (requestDispatcher != null) {
        // create servlet request
        URL fullyQualifiedServerURL;
        try {
            fullyQualifiedServerURL = getUrl();
        } catch (MalformedURLException e) {
            logger.error("FullyQualifiedServerURL is incorrect");
            return response;
        }

        final InternalHttpServletRequest servletRequest = new InternalHttpServletRequest(httpMethod,
                fullyQualifiedServerURL, "/api", endpointPath);
        servletRequest.setAttribute("org.apache.catalina.core.DISPATCHER_TYPE", DispatcherType.FORWARD); //FORWARD = 2

        try {
            insertParameters(httpMethod, queryParameters, servletRequest);
        } catch (UnsupportedEncodingException e) {
            logger.error("Can't encode parameters");
            return response;
        }

        ServletRequestEvent servletRequestEvent = new ServletRequestEvent(servletContext, servletRequest);
        RequestContextListener requestContextListener = new RequestContextListener();
        requestContextListener.requestInitialized(servletRequestEvent);

        // create servlet response
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        final InternalHttpServletResponse servletResponse = new InternalHttpServletResponse(outputStream);

        try {
            // used for calculating the response time
            long startTime = System.currentTimeMillis();

            requestDispatcher.forward(servletRequest, servletResponse);

            // get response time
            long responseTime = System.currentTimeMillis() - startTime;

            response.setStatusCode(servletResponse.getStatus());
            response.setResult(servletResponse.getContentAsString());
            response.setResponseTime(responseTime);
        } catch (ServletException ex) {
            logger.error("Failed ", ex);
            return response;
        } catch (IOException ex) {
            logger.error("Failed ", ex);
            return response;
        } finally {
            requestContextListener.requestDestroyed(servletRequestEvent);
        }

    }

    return response;
}

From source file:org.apache.click.ClickServlet.java

/**
 * Render the given page as a JSP to the response.
 *
 * @param page the page to render/*from  w ww .ja  va 2 s  .c o m*/
 * @throws Exception if an error occurs rendering the JSP
 */
protected void renderJSP(Page page) throws Exception {

    long startTime = System.currentTimeMillis();

    HttpServletRequest request = page.getContext().getRequest();

    HttpServletResponse response = page.getContext().getResponse();

    setRequestAttributes(page);

    RequestDispatcher dispatcher = null;

    String forward = page.getForward();

    // As "getTemplate" returns the page.getPath() by default, which is *.htm
    // we need to change to *.jsp in order to compare to the page.getForward()
    String jspTemplate = StringUtils.replace(page.getTemplate(), ".htm", ".jsp");

    if (forward.equals(jspTemplate)) {
        dispatcher = request.getRequestDispatcher(forward);

    } else {
        dispatcher = request.getRequestDispatcher(page.getTemplate());
    }

    dispatcher.forward(request, response);

    if (!configService.isProductionMode()) {
        HtmlStringBuffer buffer = new HtmlStringBuffer(50);
        buffer.append("renderJSP: ");
        if (!page.getTemplate().equals(page.getForward())) {
            buffer.append(page.getTemplate());
            buffer.append(",");
        }
        buffer.append(page.getForward());
        buffer.append(" - ");
        buffer.append(System.currentTimeMillis() - startTime);
        buffer.append(" ms");
        logger.info(buffer);
    }
}

From source file:nu.kelvin.jfileshare.servlets.AboutServlet.java

@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ServletContext app = getServletContext();
    RequestDispatcher disp;
    req.setAttribute("tab", "About");
    disp = app.getRequestDispatcher("/templates/About.jsp");
    HttpSession session = req.getSession();
    Conf conf = (Conf) app.getAttribute("conf");

    req.setAttribute("daysLogRetention", conf.getDaysLogRetention());

    if (session.getAttribute("user") != null) {
        Connection dbConn = null;
        PreparedStatement st = null;
        try {/*from   w w w .j a  v  a 2  s  .  c om*/
            long bytesStoreAvailable = FileSystemUtils.freeSpaceKb(conf.getPathStore()) * 1024;
            req.setAttribute("bytesStoreAvailable", FileItem.humanReadable(bytesStoreAvailable));

            dbConn = ds.getConnection();
            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as logins, cast(count(distinct payload) as char) as uniqueLogins from Logs where action=\"login\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            ResultSet rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("logins", rs.getString("logins"));
                req.setAttribute("uniqueLogins", rs.getString("uniqueLogins"));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as downloads, sum(cast(payload as unsigned)) as bytesDownloads from Logs where action=\"download\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("downloads", rs.getString("downloads"));
                req.setAttribute("bytesDownloads", FileItem.humanReadable(rs.getLong("bytesDownloads")));
            }

            st = dbConn.prepareStatement(
                    "select cast(count(1) as char) as uploads, sum(cast(payload as unsigned)) as bytesUploads from Logs where action=\"upload\" and date > (now() - INTERVAL ? DAY)");
            st.setInt(1, conf.getDaysLogRetention());
            rs = st.executeQuery();
            if (rs.first()) {
                req.setAttribute("uploads", rs.getString("uploads"));
                req.setAttribute("bytesUploads", FileItem.humanReadable(rs.getLong("bytesUploads")));
            }
            st.close();
        } catch (SQLException e) {
            logger.severe(e.toString());
        } finally {
            if (dbConn != null) {
                try {
                    dbConn.close();
                } catch (SQLException ignore) {
                }
            }
        }
    }
    disp.forward(req, resp);
}

From source file:it.classhidra.core.controller.bsController.java

public static HttpServletResponse execRedirect(i_action action_instance, ServletContext servletContext,
        HttpServletRequest request, HttpServletResponse response, boolean allowAnotherOutput)
        throws bsControllerException, ServletException, UnavailableException {

    if (action_instance == null || action_instance.get_infoaction() == null)
        return response;
    boolean intoWrapper = false;
    Object[] resultC4AOutputMode = chech4AnotherOutputMode(action_instance, servletContext, request, response,
            allowAnotherOutput);/*from   w  w  w . j av a 2  s .  c  om*/

    if (((Boolean) resultC4AOutputMode[1]).booleanValue()) {
        return response;
    }

    if (resultC4AOutputMode[0] instanceof a_ResponseWrapper) {
        response = (a_ResponseWrapper) resultC4AOutputMode[0];
        intoWrapper = true;
    }

    action_instance.onPreRedirect();
    RequestDispatcher rd = action_instance.getCurrent_redirect().redirect(servletContext,
            action_instance.get_infoaction());
    action_instance.onPostRedirect(rd);

    if (rd == null) {
        action_instance.onPreRedirectError();

        rd = action_instance.getCurrent_redirect().redirectError(servletContext,
                action_instance.get_infoaction());
        action_instance.onPostRedirectError(rd);
    }
    if (rd == null) {
        if (!action_instance.get_infoaction().getError().equals(""))
            action_instance.getCurrent_redirect().set_uriError(action_instance.get_infoaction().getError());
        else
            action_instance.getCurrent_redirect().set_uriError(getAction_config().getAuth_error());
        rd = action_instance.getCurrent_redirect().redirectError(servletContext,
                action_instance.get_infoaction());
    }

    if (rd == null)
        throw new bsControllerException("Controller generic redirect error. Action: ["
                + action_instance.get_infoaction().getPath() + "] " + action_instance.getCurrent_redirect(),
                request, iStub.log_ERROR);
    else {
        try {
            try {
                action_instance.actionBeforeRedirect(request, response);
            } catch (Exception e) {
                throw new bsControllerException(
                        "Controller generic actionBeforeRedirect error. Action: ["
                                + action_instance.get_infoaction().getPath() + "] ->" + e.toString(),
                        request, iStub.log_ERROR);
            }

            if (!intoWrapper) {

                if (!action_instance.isIncluded()) {
                    if (response.isCommitted())
                        rd.include(request, response);
                    else
                        rd.forward(request, response);
                } else
                    rd.include(request, response);

            } else {

                String tansformationElaborationMode = getAppInit().get_transf_elaborationmode();

                if (tansformationElaborationMode == null || tansformationElaborationMode.trim().length() == 0)
                    tansformationElaborationMode = CONST_TRANSFORMATION_ELMODE_INCLUDE;

                if (tansformationElaborationMode.equalsIgnoreCase(CONST_TRANSFORMATION_ELMODE_BOTH)) {
                    if (response.isCommitted())
                        rd.include(request, response);
                    else
                        rd.forward(request, response);
                }
                if (tansformationElaborationMode.equalsIgnoreCase(CONST_TRANSFORMATION_ELMODE_INCLUDE)) {
                    rd.include(request, response);
                }
                if (tansformationElaborationMode.equalsIgnoreCase(CONST_TRANSFORMATION_ELMODE_FORWARD)) {
                    rd.forward(request, response);
                }

            }

        } catch (Exception e) {
            if (intoWrapper) {
                throw new bsControllerException(
                        "Controller generic wrapped redirect error. Action: ["
                                + action_instance.get_infoaction().getPath() + "] ->" + e.toString(),
                        iStub.log_ERROR);
            } else
                throw new bsControllerException(
                        "Controller generic redirect error. Action: ["
                                + action_instance.get_infoaction().getPath() + "] ->" + e.toString(),
                        request, iStub.log_ERROR);
        }
    }
    return response;
}

From source file:hudson.model.Hudson.java

private void doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view)
        throws IOException, ServletException {
    // ability to run arbitrary script is dangerous
    checkPermission(ADMINISTER);//w w w. j  a  va 2  s .c o  m

    String text = req.getParameter("script");
    if (text != null) {
        try {
            req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, MasterComputer.localChannel));
        } catch (InterruptedException e) {
            throw new ServletException(e);
        }
    }

    view.forward(req, rsp);
}

From source file:jenkins.model.Jenkins.java

/**
 * @since 1.509.1/*from   w w  w .  j a  v  a2 s. c o m*/
 */
public static void _doScript(StaplerRequest req, StaplerResponse rsp, RequestDispatcher view,
        VirtualChannel channel, ACL acl) throws IOException, ServletException {
    // ability to run arbitrary script is dangerous
    acl.checkPermission(RUN_SCRIPTS);

    String text = req.getParameter("script");
    if (text != null) {
        if (!"POST".equals(req.getMethod())) {
            throw HttpResponses.error(HttpURLConnection.HTTP_BAD_METHOD, "requires POST");
        }

        if (channel == null) {
            throw HttpResponses.error(HttpURLConnection.HTTP_NOT_FOUND, "Node is offline");
        }

        try {
            req.setAttribute("output", RemotingDiagnostics.executeGroovy(text, channel));
        } catch (InterruptedException e) {
            throw new ServletException(e);
        }
    }

    view.forward(req, rsp);
}

From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java

public void selectCSVersionAction(HttpServletRequest request, HttpServletResponse response) {
    String selectedvalueset = null;
    String uri = null;// ww  w .  ja  v a2 s.  c  om
    String multiplematches = HTTPUtils.cleanXSS((String) request.getParameter("multiplematches"));
    if (multiplematches != null) {
        selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("valueset"));
        uri = selectedvalueset;
    } else {
        uri = HTTPUtils.cleanXSS((String) request.getParameter("vsd_uri"));
        if (uri.indexOf("|") != -1) {
            Vector u = DataUtils.parseData(uri);
            uri = (String) u.elementAt(1);
        }
    }
    request.getSession().setAttribute("vsd_uri", uri);

    try {
        String nextJSP = "/pages/resolve_value_set.jsf";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        ex.printStackTrace();
    }
}

From source file:gov.nih.nci.evs.browser.servlet.AjaxServlet.java

public void resolveValueSetAction(HttpServletRequest request, HttpServletResponse response) {
    String selectedvalueset = null;
    //String selectedvalueset = (String) request.getParameter("valueset");
    String multiplematches = HTTPUtils.cleanXSS((String) request.getParameter("multiplematches"));
    if (multiplematches != null) {
        selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("valueset"));
    } else {//w  w w  .j a va 2s .  com
        selectedvalueset = HTTPUtils.cleanXSS((String) request.getParameter("vsd_uri"));
        if (selectedvalueset != null && selectedvalueset.indexOf("|") != -1) {
            Vector u = DataUtils.parseData(selectedvalueset);
            selectedvalueset = (String) u.elementAt(1);
        }
    }
    String vsd_uri = selectedvalueset;
    request.getSession().setAttribute("selectedvalueset", selectedvalueset);

    String key = vsd_uri;

    request.getSession().setAttribute("vsd_uri", vsd_uri);
    String[] coding_scheme_ref = null;

    Vector w = DataUtils.getCodingSchemeReferencesInValueSetDefinition(vsd_uri, "PRODUCTION");
    if (w != null) {
        coding_scheme_ref = new String[w.size()];
        for (int i = 0; i < w.size(); i++) {
            String s = (String) w.elementAt(i);
            coding_scheme_ref[i] = s;

        }
    }

    if (coding_scheme_ref == null || coding_scheme_ref.length == 0) {
        String msg = "No PRODUCTION version of coding scheme is available.";
        request.getSession().setAttribute("message", msg);

        try {
            String nextJSP = "/pages/resolve_value_set.jsf";
            RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
            dispatcher.forward(request, response);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return;
        //return "resolve_value_set";
    }

    AbsoluteCodingSchemeVersionReferenceList csvList = new AbsoluteCodingSchemeVersionReferenceList();

    StringBuffer buf = new StringBuffer();

    for (int i = 0; i < coding_scheme_ref.length; i++) {
        String t = coding_scheme_ref[i];

        String delim = "|";
        if (t.indexOf("|") == -1) {
            delim = "$";
        }
        Vector u = DataUtils.parseData(t, delim);
        String uri = (String) u.elementAt(0);
        String version = (String) u.elementAt(1);
        if (version == null || version.compareTo("null") == 0) {
            version = DataUtils.getVocabularyVersionByTag(uri, "PRODUCTION");
        }
        //key = key + "|" + uri + "$" + version;
        buf.append("|" + uri + "$" + version);
        csvList.addAbsoluteCodingSchemeVersionReference(
                Constructors.createAbsoluteCodingSchemeVersionReference(uri, version));
    }
    key = key + buf.toString();

    request.getSession().setAttribute("coding_scheme_ref", coding_scheme_ref);

    //long time = System.currentTimeMillis();
    LexEVSValueSetDefinitionServices vsd_service = RemoteServerUtil.getLexEVSValueSetDefinitionServices();
    ResolvedValueSetDefinition rvsd = null;
    int lcv = 0;
    try {
        ValueSetDefinition vsd = DataUtils.findValueSetDefinitionByURI(vsd_uri);
        rvsd = vsd_service.resolveValueSetDefinition(vsd, csvList, null, null);
        if (rvsd != null) {
            ResolvedConceptReferencesIterator itr = rvsd.getResolvedConceptReferenceIterator();
            IteratorBeanManager iteratorBeanManager = null;

            if (FacesContext.getCurrentInstance() != null
                    && FacesContext.getCurrentInstance().getExternalContext() != null
                    && FacesContext.getCurrentInstance().getExternalContext().getSessionMap() != null) {
                iteratorBeanManager = (IteratorBeanManager) FacesContext.getCurrentInstance()
                        .getExternalContext().getSessionMap().get("iteratorBeanManager");
            }

            if (iteratorBeanManager == null) {
                iteratorBeanManager = new IteratorBeanManager();
                request.getSession().setAttribute("iteratorBeanManager", iteratorBeanManager);
            }

            request.getSession().setAttribute("ResolvedConceptReferencesIterator", itr);

            IteratorBean iteratorBean = iteratorBeanManager.getIteratorBean(key);
            if (iteratorBean == null) {
                iteratorBean = new IteratorBean(itr);
                iteratorBean.initialize();
                iteratorBean.setKey(key);
                iteratorBeanManager.addIteratorBean(iteratorBean);
            }

            request.getSession().setAttribute("coding_scheme_ref", coding_scheme_ref);
            request.getSession().setAttribute("ResolvedConceptReferencesIterator", itr);
            request.getSession().setAttribute("resolved_vs_key", key);

            try {
                String nextJSP = "/pages/resolved_value_set.jsf";
                RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
                dispatcher.forward(request, response);
            } catch (Exception ex) {
                ex.printStackTrace();
            }
            //return "resolved_value_set";
            return;
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    String msg = "Unable to resolve the value set " + vsd_uri;
    request.getSession().setAttribute("message", msg);

    try {
        String nextJSP = "/pages/resolved_value_set.jsf";
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
        dispatcher.forward(request, response);
    } catch (Exception ex) {
        ex.printStackTrace();
    }

    //return "resolved_value_set";
}

From source file:IdeaBroker.InserirIdeiaServlet.java

/**
 * Handles the HTTP <code>POST</code> method.
 *
 * @param request servlet request/*from ww w .  j  a v  a 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 doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    request.setCharacterEncoding("UTF-8");

    HttpSession session = request.getSession(true);

    RequestDispatcher dispatcher = null;

    String textData = null;
    String fileName = null;
    int investimento = -1, id_topico = -1;

    try { // Para apagar!!!!

        /*  isMultipart = ServletFileUpload.isMultipartContent(request);
          java.io.PrintWriter out = response.getWriter( );
          if( !isMultipart ){
            System.out.println("Multipart error ");
            return;
          }
                  
          DiskFileItemFactory factory = new DiskFileItemFactory();
          factory.setSizeThreshold(maxMemSize);
          factory.setRepository(new File("/home/joao/?rea\\ de\\ Trabalho/"));
                  
          ServletFileUpload upload = new ServletFileUpload(factory);
                  
          upload.setSizeMax(maxFileSize);
                  
          try{
                      
              List fileItems = upload.parseRequest(request);
                      
              Iterator i = fileItems.iterator();
                      
              while( i.hasNext())
              {
        FileItem fi = (FileItem)i.next();
                
        if( !fi.isFormField() )
        {
            fileName = fi.getName();
            if(!fileName.isEmpty())
            {
                 if( fileName.lastIndexOf("\\") >= 0 ){
                    file = new File( filePath + 
                    fileName.substring( fileName.lastIndexOf("\\"))) ;
                 }else{
                    file = new File( filePath + 
                    fileName.substring(fileName.lastIndexOf("\\")+1)) ;
                 }
                 fi.write(file);
            }
                
        }
        else
        {
            String inputName = (String) fi.getFieldName();
            if (inputName.equals("descricao"))
                textData = (String) fi.getString();
            else if(inputName.equals("investimento"))
                investimento = Integer.parseInt(fi.getString());
            else if(inputName.equals("id_topico"))
                id_topico = Integer.parseInt(fi.getString());
                
        }
              }*/

        /** Criar Ideia **/
        IdeaBrokerBean ideabrokerbean = (IdeaBrokerBean) session.getAttribute("ideabrokerbean");
        String username = (String) session.getAttribute("username");
        String password = (String) session.getAttribute("password");
        //System.out.println("[Servlet] Sou username =="+username+ "\n[Servlet] Token == "+ideabrokerbean.getOAuth());
        textData = request.getParameter("descricao");
        System.out.println("Descricao == " + textData);

        if ((request.getParameter("investimento") != null) && (!request.getParameter("investimento").isEmpty())
                && (ideabrokerbean.ContarLetras(request.getParameter("investimento")))) {
            System.out.println("Entra no if e investimento == " + request.getParameter("investimento"));
            investimento = Integer.parseInt(request.getParameter("investimento"));
        }

        filePath = null;
        if ((request.getParameter("id_topico") != null) && (!request.getParameter("id_topico").isEmpty()))
            id_topico = Integer.parseInt(request.getParameter("id_topico"));

        if ((textData != null && !textData.isEmpty())) {
            if (investimento != -1) {

                if ((fileName != null) && (!fileName.isEmpty())) {
                    //chama funcao que cria a ideia sem anexo
                    if (ideabrokerbean.criaIdeia(username, textData, null, id_topico, investimento))
                        dispatcher = request.getRequestDispatcher("ideia_aceite.html");
                    else
                        dispatcher = request.getRequestDispatcher("erro_ideia.html");

                    ideabrokerbean.print_service();
                } else {
                    //chama funcao que cria a ideia com anexo
                    if (ideabrokerbean.criaIdeia(username, textData, null, id_topico, investimento))
                        dispatcher = request.getRequestDispatcher("ideia_aceite.html");
                    else
                        dispatcher = request.getRequestDispatcher("erro_ideia.html");
                }
            }
        }

        //dispatcher = request.getRequestDispatcher("ideia_aceite.html");
        dispatcher.forward(request, response);

    } catch (Exception ex) {
        System.out.println(ex);
    }

}