Example usage for javax.servlet RequestDispatcher include

List of usage examples for javax.servlet RequestDispatcher include

Introduction

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

Prototype

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

Source Link

Document

Includes the content of a resource (servlet, JSP page, HTML file) in the response.

Usage

From source file:com.netspective.sparx.navigate.NavigationPage.java

/**
 * Handles the generation of the page body using the assigned page skin
 *
 * @param writer writer object to write the output to
 * @param nc     current navigation context
 *///from   w ww .  ja  v a  2s .  c  om
public void handlePageBody(Writer writer, NavigationContext nc) throws ServletException, IOException {
    // see if dynamic commands should be allowed
    HttpServletRequest request = nc.getHttpRequest();
    String panelEditorCommandSpec = request
            .getParameter(PanelEditorCommand.PANEL_EDITOR_COMMAND_REQUEST_PARAM_NAME);
    if (panelEditorCommandSpec != null && getFlags().flagIsSet(Flags.ALLOW_PANEL_EDITING)) {
        PanelEditorCommand command = new PanelEditorCommand();
        command.setParameters(panelEditorCommandSpec);
        Object panelEditorSource = null;
        // verify that this command is configured to be in this pae
        if (!getFlags().flagIsSet(Flags.VALIDATE_PANEL_EDITOR_IN_PAGE)
                || verifyPanelEditorInPage(nc, command)) {
            try {
                command.handleCommand(writer, nc, false);
            } catch (CommandException e) {
                getLog().error("Command error in body", e);
                throw new ServletException(e);
            }
            return;
        } else {
            getLog().error("Request to execute a panel editor '" + command.getPanelEditorName()
                    + "' that does not exist in page.");
        }
    }

    if (getFlags().flagIsSet(Flags.ALLOW_PAGE_CMD_PARAM)) {
        String commandSpec = request.getParameter(AbstractHttpServletCommand.PAGE_COMMAND_REQUEST_PARAM_NAME);
        if (commandSpec != null) {
            HttpServletCommand command = (HttpServletCommand) Commands.getInstance().getCommand(commandSpec);
            try {
                command.handleCommand(writer, nc, false);
            } catch (CommandException e) {
                getLog().error("Command error in body", e);
                throw new ServletException(e);
            }
            return;
        }
    }

    switch (getBodyType().getValueIndex()) {
    case NavigationPageBodyType.NONE:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName() + " class but has no body.");
        break;

    case NavigationPageBodyType.OVERRIDE:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName()
                + " class and is set as override class but does not override handlePageBody().");
        break;

    case NavigationPageBodyType.CUSTOM_HANDLER:
        for (int i = 0; i < customHandlers.size(); i++)
            ((NavigationPageBodyHandler) customHandlers.get(i)).handleNavigationPageBody(this, writer, nc);
        break;

    case NavigationPageBodyType.COMMAND:
        ValueSource commandExpr = getCommandExpr();
        if (commandExpr != null) {
            String commandText = commandExpr.getTextValue(nc);
            if (commandText != null) {
                try {
                    HttpServletCommand httpCommand = (HttpServletCommand) Commands.getInstance()
                            .getCommand(commandText);
                    httpCommand.handleCommand(writer, nc, false);
                    break;
                } catch (Exception e) {
                    getLog().error("Command error in " + this.getClass().getName(), e);
                    throw new ServletException(e);
                }
            }
        }

        // if we get to here, we don't have an expression or the expression returned null so see if we have static
        // command supplied
        try {
            ((HttpServletCommand) getCommand()).handleCommand(writer, nc, false);
        } catch (CommandException e) {
            getLog().error("Command error in body", e);
            throw new ServletException(e);
        }
        break;

    case NavigationPageBodyType.PANEL:
        getBodyPanel().render(writer, nc, nc.getActiveTheme(), HtmlPanel.RENDERFLAGS_DEFAULT);
        break;

    case NavigationPageBodyType.TEMPLATE:
        getBodyTemplate().process(writer, nc, createDefaultBodyTemplateVars(nc));
        break;

    case NavigationPageBodyType.FORWARD:
        // this should never happen -- forwards should never get to this point but we'll add a sanity check
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName()
                + " class and the body type is set to FORWARD but forwarding should happen before any response is committed.");
        break;

    case NavigationPageBodyType.INCLUDE: {
        String includeUrl = getInclude().getTextValue(nc);
        RequestDispatcher rd = request.getRequestDispatcher(includeUrl);
        ServletResponse response = nc.getResponse();
        if (writer != response.getWriter())
            response = new AlternateOutputDestServletResponse(writer, response);
        request.setAttribute(REQATTRNAME_NAVIGATION_CONTEXT, nc);
        rd.include(request, response);
        request.removeAttribute(REQATTRNAME_NAVIGATION_CONTEXT);
    }
        break;

    default:
        writer.write("Path '" + nc.getActivePathFindResults().getSearchedForPath() + "' is a "
                + this.getClass().getName() + " but doesn't know how to handle body type "
                + getBodyType().getValueIndex() + ".");
    }
}

From source file:org.apache.struts2.result.ServletDispatcherResult.java

/**
 * Dispatches to the given location. Does its forward via a RequestDispatcher. If the
 * dispatch fails a 404 error will be sent back in the http response.
 *
 * @param finalLocation the location to dispatch to.
 * @param invocation    the execution state of the action
 * @throws Exception if an error occurs. If the dispatch fails the error will go back via the
 *                   HTTP request./*w w  w  . j a v a2  s  .  c  o  m*/
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    LOG.debug("Forwarding to location: {}", finalLocation);

    PageContext pageContext = ServletActionContext.getPageContext();

    if (pageContext != null) {
        pageContext.include(finalLocation);
    } else {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

        //add parameters passed on the location to #parameters
        // see WW-2120
        if (StringUtils.isNotEmpty(finalLocation) && finalLocation.indexOf("?") > 0) {
            String queryString = finalLocation.substring(finalLocation.indexOf("?") + 1);
            HttpParameters parameters = getParameters(invocation);
            Map<String, Object> queryParams = urlHelper.parseQueryString(queryString, true);
            if (queryParams != null && !queryParams.isEmpty()) {
                parameters = HttpParameters.create(queryParams).withParent(parameters).build();
                invocation.getInvocationContext().setParameters(parameters);
                // put to extraContext, see Dispatcher#createContextMap
                invocation.getInvocationContext().getContextMap().put("parameters", parameters);
            }
        }

        // if the view doesn't exist, let's do a 404
        if (dispatcher == null) {
            LOG.warn("Location {} not found!", finalLocation);
            response.sendError(404, "result '" + finalLocation + "' not found");
            return;
        }

        //if we are inside an action tag, we always need to do an include
        Boolean insideActionTag = (Boolean) ObjectUtils
                .defaultIfNull(request.getAttribute(StrutsStatics.STRUTS_ACTION_TAG_INVOCATION), Boolean.FALSE);

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!insideActionTag && !response.isCommitted()
                && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
            request.setAttribute("struts.view_uri", finalLocation);
            request.setAttribute("struts.request_uri", request.getRequestURI());

            dispatcher.forward(request, response);
        } else {
            dispatcher.include(request, response);
        }
    }
}

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   w  w w.  jav a  2s  .  c  o  m*/
      * 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: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);// w w w.  ja  v  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:org.eclipse.equinox.http.servlet.tests.ServletTest.java

public void test_Listener9() throws Exception {
    Servlet sA = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override// w  ww .j  a  v  a 2 s . com
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {

            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/s9B");

            requestDispatcher.include(req, resp);
        }
    };
    Servlet sB = new HttpServlet() {
        private static final long serialVersionUID = 1L;

        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp)
                throws ServletException, IOException {

            PrintWriter writer = resp.getWriter();
            writer.write("S9 included");
        }
    };

    BaseServletRequestListener srl1 = new BaseServletRequestListener();

    Collection<ServiceRegistration<?>> registrations = new ArrayList<ServiceRegistration<?>>();
    try {
        Dictionary<String, String> listenerProps = new Hashtable<String, String>();
        listenerProps.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_LISTENER, "true");
        registrations
                .add(getBundleContext().registerService(ServletRequestListener.class, srl1, listenerProps));

        Dictionary<String, String> servletProps1 = new Hashtable<String, String>();
        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S9A");
        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s9A");
        registrations.add(getBundleContext().registerService(Servlet.class, sA, servletProps1));

        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_NAME, "S9B");
        servletProps1.put(HttpWhiteboardConstants.HTTP_WHITEBOARD_SERVLET_PATTERN, "/s9B");
        registrations.add(getBundleContext().registerService(Servlet.class, sB, servletProps1));

        String result = requestAdvisor.request("s9A");
        Assert.assertEquals("S9 included", result);

        Assert.assertEquals(0, srl1.number.get());

    } finally {
        for (ServiceRegistration<?> registration : registrations) {
            registration.unregister();
        }
    }
}

From source file:com.tmwsoft.sns.web.action.MainAction.java

private ActionForward executeTask(HttpServletRequest request, HttpServletResponse response,
        Map<String, Object> task, Map<String, Object> space) {
    request.setAttribute("task", task);
    request.setAttribute("space", space);
    request.setAttribute("mainService", mainService);
    request.setAttribute("dataBaseService", dataBaseService);
    RequestDispatcher dispatcher = request
            .getRequestDispatcher("/source/task/" + ((String) task.get("filename")));
    try {/*from w  ww.  j av  a2 s  .  c  om*/
        dispatcher.include(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        return showMessage(request, response, e.getMessage());
    }
    return null;
}

From source file:cn.jcenterhome.web.action.CpAction.java

private ActionForward executeTask(HttpServletRequest request, HttpServletResponse response,
        Map<String, Object> task, Map<String, Object> space) {
    request.setAttribute("task", task);
    request.setAttribute("space", space);
    request.setAttribute("cpService", cpService);
    request.setAttribute("dataBaseService", dataBaseService);
    RequestDispatcher dispatcher = request
            .getRequestDispatcher("/source/task/" + ((String) task.get("filename")));
    try {/*  w  ww .  j a v a  2  s  .  c  o  m*/
        dispatcher.include(request, response);
    } catch (Exception e) {
        e.printStackTrace();
        return showMessage(request, response, e.getMessage());
    }
    return null;
}