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:org.sc.probro.servlets.SkeletonServlet.java

public JSONObject getLocalJSON(HttpServletRequest req, String path)
        throws ServletException, IOException, JSONException, BrokerException {
    RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(path);
    DummyServletResponse response = new DummyServletResponse();
    dispatcher.include(req, response);

    if (response.getStatus() != HttpServletResponse.SC_OK) {
        throw new BrokerException(response.getStatus(), response.getValue());
    }//from w w  w . j a v a 2 s . co m

    String value = response.getValue();
    Log.info(value);
    return new JSONObject(value);
}

From source file:org.dspace.app.webui.jsptag.LayoutTag.java

public int doEndTag() throws JspException {
    // Context objects
    ServletRequest request = pageContext.getRequest();
    HttpServletResponse response = (HttpServletResponse) pageContext.getResponse();
    ServletConfig config = pageContext.getServletConfig();

    // header file
    String header = templatePath + "header-default.jsp";

    // Choose default style unless one is specified
    if (style != null) {
        header = templatePath + "header-" + style.toLowerCase() + ".jsp";
    }/*w w w  .j  a  v a  2s  . com*/

    if (sidebar != null) {
        request.setAttribute("dspace.layout.sidebar", sidebar);
    }

    // Now include the header
    try {
        // Set headers to prevent browser caching, if appropriate
        if ((noCache != null) && noCache.equalsIgnoreCase("true")) {
            response.addDateHeader("expires", 1);
            response.addHeader("Pragma", "no-cache");
            response.addHeader("Cache-control", "no-store");
        }

        // Ensure the HTTP header will declare that UTF-8 is used
        // in the response.
        response.setContentType("text/html; charset=UTF-8");

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(header);

        rd.include(request, response);

        //pageContext.getOut().write(getBodyContent().getString());
        getBodyContent().writeOut(pageContext.getOut());
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    } catch (ServletException se) {
        log.warn("Exception", se.getRootCause());
        throw new JspException("Got ServletException: " + se);
    }

    // Footer file to use
    String footer = templatePath + "footer-default.jsp";

    // Choose default flavour unless one is specified
    if (style != null) {
        footer = templatePath + "footer-" + style.toLowerCase() + ".jsp";
    }

    try {
        // Ensure body is included before footer
        pageContext.getOut().flush();

        RequestDispatcher rd = config.getServletContext().getRequestDispatcher(footer);

        rd.include(request, response);
    } catch (ServletException se) {
        throw new JspException("Got ServletException: " + se);
    } catch (IOException ioe) {
        throw new JspException("Got IOException: " + ioe);
    }

    style = null;
    title = null;
    sidebar = null;
    navbar = null;
    locbar = null;
    parentTitle = null;
    parentLink = null;
    noCache = null;
    feedData = null;
    return EVAL_PAGE;
}

From source file:org.jahia.services.notification.HttpClientService.java

/**
 * Retrieves resource content, specified by the provided URL.
 *
 * @param url the URL of the resource to be retrieved
 * @return the string content of the resource
 * @throws {@link IllegalArgumentException} in case of a malformed URL
 *//* ww  w. j  a  v  a2 s. c o m*/
public String getResourceAsString(String url, HttpServletRequest request, HttpServletResponse response)
        throws IllegalArgumentException {
    if (StringUtils.isEmpty(url)) {
        throw new IllegalArgumentException("Provided URL is null");
    }
    if (isAbsoluteUrl(url)) {
        return getAbsoluteResourceAsString(url);
    }
    if (!url.startsWith("/")) {
        throw new IllegalArgumentException("Provided relative URL does not start with a '/'");
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Asked to get content from the URL: " + url);
    }

    String content = null;

    RequestDispatcher rd = request.getRequestDispatcher(url);
    if (rd != null) {
        StringResponseWrapper wrapper = new StringResponseWrapper(response);
        try {
            rd.include(request, wrapper);
            if (wrapper.getStatus() < 200 || wrapper.getStatus() > 299) {
                logger.warn("Unable to get the content of the resource " + url + ". Got response status code: "
                        + wrapper.getStatus());
            } else {
                content = wrapper.getString();
            }
        } catch (Exception e) {
            logger.warn("Unable to get the content of the resource " + url + ". Cause: " + e.getMessage(), e);
        }
    } else {
        logger.warn("Unable to get a RequestDispatcher for the path " + url);
    }

    if (logger.isDebugEnabled()) {
        logger.debug("Retrieved " + (content != null ? content.length() : 0) + " characters as a response");
        if (logger.isTraceEnabled()) {
            logger.trace("Content:\n" + content);
        }
    }

    return content;
}

From source file:cn.org.pomer.web.DirectResult.java

private void doDispatcher(HttpServletResponse response, HttpServletRequest request, String resultCodeAsLocation)
        throws IOException, ServletException {
    if (_log.isInfoEnabled()) {
        _log.info("Forwarding to location:" + resultCodeAsLocation);
    }/*from   ww w  . j av a2  s .c  om*/

    PageContext pageContext = ServletActionContext.getPageContext();
    if (pageContext != null) {
        pageContext.include(resultCodeAsLocation);
        return;
    }

    RequestDispatcher dispatcher = request.getRequestDispatcher(resultCodeAsLocation);
    if (dispatcher == null) {
        response.sendError(404, "result '" + resultCodeAsLocation + "' not found");
        return;
    }

    if (!response.isCommitted() && (request.getAttribute("javax.servlet.include.servlet_path") == null)) {
        request.setAttribute("struts.view_uri", resultCodeAsLocation);
        request.setAttribute("struts.request_uri", request.getRequestURI());

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

From source file:org.nextframework.view.BaseTag.java

private void dispatchToTemplate(String template, PrintWriter writer) throws ServletException, IOException {
    WrappedWriterResponse response = new WrappedWriterResponse(getResponse(), writer);
    RequestDispatcher requestDispatcher = null;
    requestDispatcher = getRequest().getRequestDispatcher(template);
    requestDispatcher.include(getRequest(), response);
}

From source file:org.zkoss.zkgrails.ZKGrailsPageFilter.java

protected void applyDecorator(Page page, Decorator decorator, HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {
    final String uriPath = decorator.getURIPath();
    if (uriPath != null && uriPath.endsWith(".gsp")) {
        request.setAttribute(PAGE, page);

        detectContentTypeFromPage(page, response);

        RequestDispatcher rd = request.getRequestDispatcher(decorator.getURIPath());
        if (!response.isCommitted()) {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rendering layout using forward: " + decorator.getURIPath());
            }//from ww w .j av a2 s . c  o  m
            rd.forward(request, response);
        } else {
            if (LOG.isDebugEnabled()) {
                LOG.debug("Rendering layout using include: " + decorator.getURIPath());
            }
            request.setAttribute(GrailsApplicationAttributes.GSP_TO_RENDER, decorator.getURIPath());
            rd.include(request, response);
            request.removeAttribute(GrailsApplicationAttributes.GSP_TO_RENDER);
        }

        // set the headers specified as decorator init params
        while (decorator.getInitParameterNames().hasNext()) {
            String initParam = (String) decorator.getInitParameterNames().next();
            if (initParam.startsWith("header.")) {
                response.setHeader(initParam.substring(initParam.indexOf('.')),
                        decorator.getInitParameter(initParam));
            }
        }
        request.removeAttribute(PAGE);
    } else {

        super.applyDecorator(page, decorator, request, response);

    }
}

From source file:com.wabacus.system.assistant.WabacusAssistant.java

public void includeDynTpl(ReportRequest rrequest, AbsComponentType comObj, String dyntplpath) {
    if (dyntplpath == null || dyntplpath.trim().equals("")
            || dyntplpath.trim().equals(Consts_Private.REPORT_TEMPLATE_NONE)) {
        return;//from   w  ww  .ja v a2  s. c  om
    }
    if (rrequest.isExportToLocalFile()) {
        throw new WabacusRuntimeException("????"
                + comObj.getConfigBean().getPath() + "????");
    }
    rrequest.getRequest().setAttribute("WX_COMPONENT_OBJ", comObj);
    try {
        RequestDispatcher rd = rrequest.getRequest().getRequestDispatcher(dyntplpath.trim());
        rd.include(rrequest.getRequest(), rrequest.getWResponse().getResponse());
    } catch (Exception e) {
        throw new WabacusRuntimeException(
                "?" + dyntplpath + "" + comObj.getConfigBean().getPath() + "", e);
    }
}

From source file:org.apache.velocity.tools.view.ImportSupport.java

/**
 *
 * @param url the URL resource to return as string
 * @return the URL resource as string//ww  w  .  j a v a  2  s. c o  m
 * @throws IOException
 * @throws java.lang.Exception
 */
protected String acquireString(String url) throws IOException, Exception {
    // Record whether our URL is absolute or relative
    if (isAbsoluteUrl(url)) {
        // for absolute URLs, delegate to our peer
        BufferedReader r = null;
        try {
            r = new BufferedReader(acquireReader(url));
            StringBuffer sb = new StringBuffer();
            int i;
            // under JIT, testing seems to show this simple loop is as fast
            // as any of the alternatives
            while ((i = r.read()) != -1) {
                sb.append((char) i);
            }
            return sb.toString();
        } finally {
            if (r != null) {
                try {
                    r.close();
                } catch (IOException ioe) {
                    LOG.error("Could not close reader.", ioe);
                }
            }
        }
    } else // handle relative URLs ourselves
    {
        // URL is relative, so we must be an HTTP request
        if (!(request instanceof HttpServletRequest && response instanceof HttpServletResponse)) {
            throw new Exception("Relative import from non-HTTP request not allowed");
        }

        // retrieve an appropriate ServletContext
        // normalize the URL if we have an HttpServletRequest
        if (!url.startsWith("/")) {
            String sp = ((HttpServletRequest) request).getServletPath();
            url = sp.substring(0, sp.lastIndexOf('/')) + '/' + url;
        }

        // strip the session id from the url
        url = stripSession(url);

        // from this context, get a dispatcher
        RequestDispatcher rd = application.getRequestDispatcher(url);
        if (rd == null) {
            throw new Exception("Couldn't get a RequestDispatcher for \"" + url + "\"");
        }

        // include the resource, using our custom wrapper
        ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse) response);
        try {
            rd.include(request, irw);
        } catch (IOException ex) {
            throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex);
        } catch (RuntimeException ex) {
            throw new Exception("Problem importing the relative URL \"" + url + "\". " + ex);
        }

        // disallow inappropriate response codes per JSTL spec
        if (irw.getStatus() < 200 || irw.getStatus() > 299) {
            throw new Exception("Invalid response code '" + irw.getStatus() + "' for \"" + url + "\"");
        }

        // recover the response String from our wrapper
        return irw.getString();
    }
}

From source file:com.jeeframework.webframework.filter.dispatcher.JSONJspServletDispatcherResult.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.//ww  w .j  a va  2 s.com
 * 
 * @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.
 */
public void doExecute(String finalLocation, ActionInvocation invocation) throws Exception {
    if (log.isDebugEnabled()) {
        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();

        String curFileName = StringUtils.getFileNamePreffix(finalLocation);
        String curFileSuffix = StringUtils.getFilenameExtension(finalLocation);
        String dstFile = curFileName;

        if (curFileName.startsWith(JSONJspServletDispatcherResult.JSONJSP_PREFIX)
                && curFileName.length() > JSONJspServletDispatcherResult.JSONJSP_PREFIX.length()) {
            dstFile = curFileName.substring(JSONJspServletDispatcherResult.JSONJSP_PREFIX.length());
        }
        if (curFileName.endsWith(JSONJspServletDispatcherResult.JSONJSP_SUFFIX)
                && curFileName.length() > JSONJspServletDispatcherResult.JSONJSP_SUFFIX.length()) {
            dstFile = dstFile.substring(0,
                    dstFile.length() - JSONJspServletDispatcherResult.JSONJSP_SUFFIX.length());
        }

        String webroot = System.getProperty(StrutsPrepareAndExecuteFilterWrapper.CUR_DEFAULT_WEBROOT_KEY);
        if (!webroot.endsWith("/") && !webroot.endsWith("\\")) {
            webroot = webroot + "/";
        }

        String dstFilePath = webroot + finalLocation;

        File dstCurjsp = new File(dstFilePath);
        // && !dstCurjsp.exists()
        if (!dstCurjsp.exists()) {
            try {
                String srcFilePath = webroot;//
                if (!(dstFile.startsWith("/") || dstFile.startsWith("\\"))) {
                    srcFilePath = srcFilePath + "/";
                }
                srcFilePath = srcFilePath + dstFile + "." + curFileSuffix;

                File srcCurjsp = new File(srcFilePath);

                String srcCurjspContent = FileUtils.readFileToString(srcCurjsp,
                        StrutsPrepareAndExecuteFilterWrapper.FILE_ENCODING);
                srcCurjspContent = srcCurjspContent.replaceAll("[\r\n\t]", "");

                FileUtils.writeStringToFile(dstCurjsp, srcCurjspContent,
                        StrutsPrepareAndExecuteFilterWrapper.FILE_ENCODING);

            } catch (IOException e) {
                e.printStackTrace();
                System.out.println("? jsonjsp " + dstFilePath + "error");
            }
        }

        RequestDispatcher dispatcher = request.getRequestDispatcher(finalLocation);

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

            return;
        }

        // If we're included, then include the view
        // Otherwise do forward
        // This allow the page to, for example, set content type
        if (!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:com.adobe.acs.commons.errorpagehandler.impl.ErrorPageHandlerImpl.java

@Override
public void includeUsingGET(final SlingHttpServletRequest request, final SlingHttpServletResponse response,
        final String path) {
    if (cache == null || errorImagesEnabled && this.isImageRequest(request)) {
        final RequestDispatcher dispatcher = request.getRequestDispatcher(path);

        if (dispatcher != null) {
            try {
                dispatcher.include(new GetRequest(request), response);
            } catch (Exception e) {
                log.debug("Exception swallowed while including error page", e);
            }//from   ww w.  j  av  a2 s . co  m
        }
    } else {
        final String responseData = cache.get(path, new GetRequest(request), response);
        try {
            response.getWriter().write(responseData);
        } catch (Exception e) {
            log.info("Exception swallowed while including error page", e);
        }
    }
}