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.codehaus.groovy.grails.web.sitemesh.GrailsPageFilter.java

@Override
protected DecoratorSelector initDecoratorSelector(SiteMeshWebAppContext webAppContext) {
    // TODO: Remove heavy coupling on horrible SM2 Factory
    final Factory factory = Factory.getInstance(new Config(filterConfig));
    factory.refresh();/*from  ww  w  . java 2  s .  co  m*/
    return new DecoratorMapper2DecoratorSelector(factory.getDecoratorMapper()) {
        @Override
        public Decorator selectDecorator(Content content, SiteMeshContext context) {
            SiteMeshWebAppContext webAppContext = (SiteMeshWebAppContext) context;
            final com.opensymphony.module.sitemesh.Decorator decorator = factory.getDecoratorMapper()
                    .getDecorator(webAppContext.getRequest(), content2htmlPage(content));
            if (decorator == null || decorator.getPage() == null) {
                return new GrailsNoDecorator();
            } else {
                return new OldDecorator2NewDecorator(decorator) {
                    @Override
                    protected void render(Content content, HttpServletRequest request,
                            HttpServletResponse response, ServletContext servletContext,
                            SiteMeshWebAppContext webAppContext) throws IOException, ServletException {

                        HTMLPage htmlPage = content2htmlPage(content);
                        request.setAttribute(PAGE, htmlPage);

                        // see if the URI path (webapp) is set
                        if (decorator.getURIPath() != null) {
                            // in a security conscious environment, the servlet container
                            // may return null for a given URL
                            if (servletContext.getContext(decorator.getURIPath()) != null) {
                                servletContext = servletContext.getContext(decorator.getURIPath());
                            }
                        }
                        // get the dispatcher for the decorator
                        RequestDispatcher dispatcher = servletContext.getRequestDispatcher(decorator.getPage());
                        if (response.isCommitted()) {
                            dispatcher.include(request, response);
                        } else {
                            dispatcher.forward(request, response);
                        }

                        request.removeAttribute(PAGE);
                    }

                };
            }
        }
    };
}

From source file:org.apache.struts.chain.commands.servlet.PerformForward.java

private void handleAsInclude(String uri, ServletContext servletContext, HttpServletRequest request,
        HttpServletResponse response) throws IOException, ServletException {
    RequestDispatcher rd = servletContext.getRequestDispatcher(uri);

    if (rd == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error getting RequestDispatcher for " + uri);
        return;// w w w  .  j  ava2  s  .c o m
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("Including " + uri);
    }

    rd.include(request, response);
}

From source file:com.bstek.dorado.view.resolver.HtmlViewResolver.java

@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
    if (touchUserAgentArray != null) {
        String userAgent = request.getHeader("user-agent");
        for (String mobile : touchUserAgentArray) {
            if (StringUtils.containsIgnoreCase(userAgent, mobile)) {
                Context context = Context.getCurrent();
                context.setAttribute("com.bstek.dorado.view.resolver.HtmlViewResolver.isTouch", true);
                break;
            }/*ww w .  ja  va2  s.co m*/
        }
    }

    String uri = getRelativeRequestURI(request);
    if (!PathUtils.isSafePath(uri)) {
        throw new PageAccessDeniedException("[" + request.getRequestURI() + "] Request forbidden.");
    }

    if (shouldAutoLoadDataConfigResources) {
        if (System.currentTimeMillis() - lastValidateTimestamp > MIN_DATA_CONFIG_VALIDATE_SECONDS
                * ONE_SECOND) {
            lastValidateTimestamp = System.currentTimeMillis();

            ((ReloadableDataConfigManagerSupport) dataConfigManager).validateAndReloadConfigs();

            if (dataConfigManager instanceof ConfigurableDataConfigManager) {
                ((ConfigurableDataConfigManager) dataConfigManager).recalcConfigLocations();
            }
        }
    }

    String viewName = extractViewName(uri);

    if (listeners != null) {
        synchronized (listeners) {
            for (ViewResolverListener listener : listeners) {
                listener.beforeResolveView(viewName);
            }
        }
    }

    DoradoContext context = DoradoContext.getCurrent();
    ViewConfig viewConfig = null;
    try {
        viewConfig = viewConfigManager.getViewConfig(viewName);
    } catch (FileNotFoundException e) {
        throw new PageNotFoundException(e);
    }

    View view = viewConfig.getView();

    ViewCacheMode cacheMode = ViewCacheMode.none;
    ViewCache cache = view.getCache();
    if (cache != null && cache.getMode() != null) {
        cacheMode = cache.getMode();
    }

    if (ViewCacheMode.clientSide.equals(cacheMode)) {
        long maxAge = cache.getMaxAge();
        if (maxAge <= 0) {
            maxAge = Configure.getLong("view.clientSideCache.defaultMaxAge", 300);
        }

        response.addHeader(HttpConstants.CACHE_CONTROL, HttpConstants.MAX_AGE + maxAge);
    } else {
        response.addHeader(HttpConstants.CACHE_CONTROL, HttpConstants.NO_CACHE);
        response.addHeader("Pragma", "no-cache");
        response.addHeader("Expires", "0");
    }

    String pageTemplate = view.getPageTemplate();
    String pageUri = view.getPageUri();
    if (StringUtils.isNotEmpty(pageTemplate) && StringUtils.isNotEmpty(pageUri)) {
        throw new IllegalArgumentException(
                "Can not set [view.pageTemplate] and [view.pageUri] at the same time.");
    }

    if (StringUtils.isNotEmpty(pageUri)) {
        ServletContext servletContext = context.getServletContext();
        RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(pageUri);
        request.setAttribute(View.class.getName(), view);
        requestDispatcher.include(request, response);
    } else {
        org.apache.velocity.context.Context velocityContext = velocityHelper.getContext(view, request,
                response);

        Template template = getPageTemplate(pageTemplate);
        PrintWriter writer = getWriter(request, response);
        try {
            template.merge(velocityContext, writer);
        } finally {
            writer.flush();
            writer.close();
        }
    }

    if (listeners != null) {
        synchronized (listeners) {
            for (ViewResolverListener listener : listeners) {
                listener.afterResolveView(viewName, view);
            }
        }
    }
}

From source file:org.apache.struts.chain.servlet.TilesPreProcessor.java

/**
 * <p>Do an include of specified URI using a <code>RequestDispatcher</code>.</p>
 *
 * @param swcontext a chain servlet/web context
 * @param uri Context-relative URI to include
 *//*w  ww  .j  a v  a2s .co m*/
protected void doInclude(ServletWebContext swcontext, String uri) throws IOException, ServletException {

    HttpServletRequest request = swcontext.getRequest();

    // Unwrap the multipart request, if there is one.
    if (request instanceof MultipartRequestWrapper) {
        request = ((MultipartRequestWrapper) request).getRequest();
    }

    HttpServletResponse response = swcontext.getResponse();
    RequestDispatcher rd = swcontext.getContext().getRequestDispatcher(uri);
    if (rd == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                "Error getting RequestDispatcher for " + uri);
        return;
    }
    rd.include(request, response);
}

From source file:org.apache.struts2.util.StrutsUtil.java

/**
 * @deprecated the request and response are stored in this util class, please use include(string)
 *///www.  jav  a  2  s. c  o  m
public String include(Object aName, HttpServletRequest aRequest, HttpServletResponse aResponse)
        throws Exception {
    try {
        RequestDispatcher dispatcher = aRequest.getRequestDispatcher(aName.toString());

        if (dispatcher == null) {
            throw new IllegalArgumentException("Cannot find included file " + aName);
        }

        ResponseWrapper responseWrapper = new ResponseWrapper(aResponse);

        dispatcher.include(aRequest, responseWrapper);

        return responseWrapper.getData();
    } catch (Exception e) {
        e.printStackTrace();
        throw e;
    }
}

From source file:org.dd4t.springmvc.view.impl.JSPQueryViewHandler.java

@Override
public String handleView(GenericPage page, Component model, String ViewID, HttpServletRequest req,
        HttpServletResponse res) throws Exception {

    // first, run the query
    NumericField schemaField = (NumericField) ((GenericComponent) model).getContent().get("schema");
    int schemaId = schemaField.getNumericValues().get(0).intValue();
    NumericField maxResultsField = (NumericField) ((GenericComponent) model).getContent().get("schema");
    int max = maxResultsField.getNumericValues().get(0).intValue();
    Query query = new Query();
    Criteria c = new ItemSchemaCriteria(schemaId);
    query.setCriteria(c);// ww  w.  j ava  2s.c o m
    query.addLimitFilter(new LimitFilter(max * 3));
    String[] ids = query.executeQuery();

    List<GenericComponent> queryModel = new ArrayList<GenericComponent>();
    int counter = 0;
    for (String id : ids) {
        logger.debug("found uri " + id);
        try {
            GenericComponent comp = (GenericComponent) this.getComponentFactory().getComponent(id);
            queryModel.add(comp);
            if (++counter > max)
                break;
        } catch (ItemNotFoundException e) {
            logger.warn("found component without valid CP: " + id);
        }
    }

    // retrieve dispatcher to component JSP view
    // RequestDispatcher dispatcher =
    // config.getServletContext().getRequestDispatcher("/component/JSP/"+ViewID+".jsp");
    RequestDispatcher dispatcher = req.getSession().getServletContext()
            .getRequestDispatcher("/components/jsp/" + ViewID + ".jsp");

    // create wrapper (acts as response, but stores output in a
    // CharArrayWriter)
    CharResponseWrapper wrapper = new CharResponseWrapper(res);
    try {
        req.setAttribute("Component", model);
        req.setAttribute("Results", queryModel);
        // run the include
        dispatcher.include(req, wrapper);
    } catch (Exception ex) {
        logger.error("error including", ex);
        return ex.getMessage();
    }

    // and return the wrapper
    return wrapper.toString();
}

From source file:ch.entwine.weblounge.common.impl.content.page.AbstractRenderer.java

/**
 * Convenience implementation for JSP renderer. The <code>renderer</code> url
 * is first looked up using the available language information from request
 * and site. Then it is included in the response.
 * // w w  w. j a  va  2s. co  m
 * @param request
 *          the request
 * @param response
 *          the response
 * @param renderer
 *          the renderer
 * @throws RenderException
 *           if an error occurs while rendering
 */
protected void includeJSP(WebloungeRequest request, WebloungeResponse response, URL renderer)
        throws RenderException {

    Site site = request.getSite();
    Language language = request.getLanguage();
    File jsp = null;

    try {
        if ("file".equals(renderer.getProtocol())) {
            // Find the best match for the template
            String[] filePaths = LanguageUtils.getLanguageVariants(renderer.toExternalForm(), language,
                    site.getDefaultLanguage());
            for (String path : filePaths) {
                logger.trace("Looking for jsp {}", path);
                File f = new File(path);
                if (f.exists()) {
                    logger.debug("Found jsp at {}", path);
                    jsp = f;
                    break;
                }
            }

            // Did we find a suitable JSP?
            if (jsp == null) {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                throw new RenderException(this, "No suitable java server page found for " + renderer
                        + " and language '" + language.getIdentifier() + "'");
            }

            // Check readability
            if (!jsp.canRead()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                throw new RenderException(this, "Java server page at " + jsp + " cannot be read");
            }

            // No directory listings allowed
            if (!jsp.isFile()) {
                response.sendError(HttpServletResponse.SC_FORBIDDEN);
                throw new RenderException(this, "Java server page at " + jsp + " is not a file");
            }

            renderer = jsp.toURI().toURL();
        }

        // Prepare a request to site resources
        String servletPath = "/weblounge-sites/" + site.getIdentifier();
        String requestPath = renderer.getPath();
        requestPath = requestPath.substring(servletPath.length());
        requestPath = UrlUtils.concat(Site.BUNDLE_PATH, requestPath);
        SiteRequestWrapper siteRequest = new SiteRequestWrapper(request, requestPath, false);

        RequestDispatcher dispatcher = request.getRequestDispatcher(servletPath);
        if (dispatcher == null)
            throw new IllegalStateException("No dispatcher found for site '" + site + "'");

        // Finally serve the JSP
        logger.debug("Including jsp {}", renderer);
        dispatcher.include(siteRequest, response);

        response.getWriter().flush();
    } catch (IOException e) {
        logger.error("Exception while including jsp {}", renderer, e);
    } catch (Throwable t) {
        throw new RenderException(this, t);
    }
}

From source file:org.apache.sling.scripting.jsp.taglib.IncludeTagHandler.java

protected void dispatch(RequestDispatcher dispatcher, ServletRequest request, ServletResponse response)
        throws IOException, ServletException {

    // optionally flush
    if (flush && !(pageContext.getOut() instanceof BodyContent)) {
        // might throw an IOException of course
        pageContext.getOut().flush();//  w  w w  .j  a  v  a  2  s. c o  m
    }
    if (var == null) {
        dispatcher.include(request, response);
    } else {
        String encoding = response.getCharacterEncoding();
        BufferedServletOutputStream bsops = new BufferedServletOutputStream(encoding);
        try {
            CaptureResponseWrapper wrapper = new CaptureResponseWrapper((HttpServletResponse) response, bsops);
            dispatcher.include(request, wrapper);
            if (!wrapper.isBinaryResponse()) {
                wrapper.flushBuffer();
                pageContext.setAttribute(var, bsops.getBuffer(), scope);
            }
        } finally {
            IOUtils.closeQuietly(bsops);
        }
    }
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.DashboardPropertyListController.java

public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    try {// www .ja v  a 2 s .  co  m
        super.doGet(req, res);
        Object obj = req.getAttribute("entity");
        if (obj == null || !(obj instanceof Individual))
            throw new HelpException(
                    "EntityMergedPropertyListController requires request.attribute 'entity' to be of" + " type "
                            + Individual.class.getName());
        Individual subject = (Individual) obj;

        String groupForUngroupedProperties = null;
        String unassignedStr = req.getParameter("unassignedPropsGroupName");
        if (unassignedStr != null && unassignedStr.length() > 0) {
            groupForUngroupedProperties = unassignedStr;
            // pass this on to dashboardPropsList.jsp
            req.setAttribute("unassignedPropsGroupName", unassignedStr);
            log.debug("found temp group parameter \"" + unassignedStr + "\" for unassigned properties");
        }

        boolean groupedMode = false;
        String groupedStr = req.getParameter("grouped");
        if (groupedStr != null && groupedStr.equalsIgnoreCase("true")) {
            groupedMode = true;
        }

        boolean onlyPopulatedProps = true;
        String allPossiblePropsStr = req.getParameter("allProps");
        if (allPossiblePropsStr != null && allPossiblePropsStr.length() > 0) {
            log.debug("found props inclusion parameter \"" + allPossiblePropsStr + "\"");
            if (allPossiblePropsStr.equalsIgnoreCase("true")) {
                onlyPopulatedProps = false;
            }
        }

        VitroRequest vreq = new VitroRequest(req);
        WebappDaoFactory wdf = vreq.getWebappDaoFactory();

        PropertyGroupDao pgDao = null;
        List<PropertyGroup> groupsList = null;
        if (groupedMode) {
            pgDao = wdf.getPropertyGroupDao();
            groupsList = pgDao.getPublicGroups(false); // may be returned empty but not null
        }

        PropertyInstanceDao piDao = wdf.getPropertyInstanceDao();
        ObjectPropertyDao opDao = wdf.getObjectPropertyDao();

        // set up a new list for the combined object and data properties
        List<Property> mergedPropertyList = new ArrayList<Property>();

        if (onlyPopulatedProps) {
            // now first get the properties this entity actually has, presumably populated with statements 
            List<ObjectProperty> objectPropertyList = subject.getObjectPropertyList();
            for (ObjectProperty op : objectPropertyList) {
                op.setLabel(op.getDomainPublic());
                mergedPropertyList.add(op);
            }
        } else {
            log.debug("getting all possible object property choices");
            Collection<PropertyInstance> allPropInstColl = piDao
                    .getAllPossiblePropInstForIndividual(subject.getURI());
            if (allPropInstColl != null) {
                for (PropertyInstance pi : allPropInstColl) {
                    if (pi != null) {
                        ObjectProperty op = opDao.getObjectPropertyByURI(pi.getPropertyURI());
                        op.setLabel(op.getDomainPublic()); // no longer relevant: pi.getSubjectSide() ? op.getDomainPublic() : op.getRangePublic());
                        mergedPropertyList.add(op);
                    } else {
                        log.error(
                                "a property instance in the Collection created by PropertyInstanceDao.getAllPossiblePropInstForIndividual() is unexpectedly null");
                    }
                }
            } else {
                log.error(
                        "a null Collection is returned from PropertyInstanceDao.getAllPossiblePropInstForIndividual()");
            }
        }

        DataPropertyDao dpDao = wdf.getDataPropertyDao();
        if (onlyPopulatedProps) {
            // now do much the same with data properties: get the list of populated data properties, then add in placeholders for missing ones
            List<DataProperty> dataPropertyList = subject.getDataPropertyList();
            for (DataProperty dp : dataPropertyList) {
                dp.setLabel(dp.getPublicName());
                mergedPropertyList.add(dp);
            }
        } else {
            log.debug("getting all possible data property choices");
            Collection<DataProperty> allDatapropColl = dpDao
                    .getAllPossibleDatapropsForIndividual(subject.getURI());
            if (allDatapropColl != null) {
                for (DataProperty dp : allDatapropColl) {
                    if (dp != null) {
                        dp.setLabel(dp.getPublicName());
                        mergedPropertyList.add(dp);
                    } else {
                        log.error(
                                "a data property in the Collection created in DataPropertyDao.getAllPossibleDatapropsForIndividual() is unexpectedly null)");
                    }
                }
            } else {
                log.error(
                        "a null Collection is returned from DataPropertyDao.getAllPossibleDatapropsForIndividual())");
            }
        }

        if (mergedPropertyList != null) {
            try {
                Collections.sort(mergedPropertyList, new PropertyRanker(vreq));
            } catch (Exception ex) {
                log.error("Exception sorting merged property list: " + ex.getMessage());
            }
            if (groupedMode) {
                int groupsCount = 0;
                try {
                    groupsCount = populateGroupsListWithProperties(pgDao, groupsList, mergedPropertyList,
                            groupForUngroupedProperties);
                } catch (Exception ex) {
                    log.error(
                            "Exception on trying to populate groups list with properties: " + ex.getMessage());
                    ex.printStackTrace();
                }
                try {
                    int removedCount = pgDao.removeUnpopulatedGroups(groupsList);
                    if (removedCount == 0) {
                        log.warn("Of " + groupsCount + " groups, none removed by removeUnpopulatedGroups");
                        /*  } else {
                                log.warn("Of "+groupsCount+" groups, "+removedCount+" removed by removeUnpopulatedGroups"); */
                    }
                    groupsCount -= removedCount;
                    req.setAttribute("groupsCount", new Integer(groupsCount));
                    if (groupsCount > 0) { //still
                        for (PropertyGroup g : groupsList) {
                            int statementCount = 0;
                            if (g.getPropertyList() != null && g.getPropertyList().size() > 0) {
                                for (Property p : g.getPropertyList()) {
                                    if (p instanceof ObjectProperty) {
                                        ObjectProperty op = (ObjectProperty) p;
                                        if (op.getObjectPropertyStatements() != null
                                                && op.getObjectPropertyStatements().size() > 0) {
                                            statementCount += op.getObjectPropertyStatements().size();
                                        }
                                    }
                                }
                            }
                            g.setStatementCount(statementCount);
                        }
                    }
                } catch (Exception ex) {
                    log.error("Exception on trying to prune groups list with properties: " + ex.getMessage());
                }
                mergedPropertyList.clear();
            }
            if (groupedMode) {
                req.setAttribute("groupsList", groupsList);
            } else {
                req.setAttribute("dashboardPropertyList", mergedPropertyList);
            }
        }
        req.setAttribute("entity", subject);

        RequestDispatcher rd = req.getRequestDispatcher(Controllers.DASHBOARD_PROP_LIST_JSP);
        rd.include(req, res);
    } catch (HelpException help) {
        doHelp(res);
    } catch (Throwable e) {
        req.setAttribute("javax.servlet.jsp.jspException", e);
        RequestDispatcher rd = req.getRequestDispatcher("/error.jsp");
        rd.forward(req, res);
    }
}

From source file:org.apache.tapestry.jsp.URLRetriever.java

/**
 *  Invokes the servlet to retrieve the URL.  The URL is inserted
 *  into the output (as with/*from  w  w  w  .j  ava2s.com*/
 *  {@link RequestDispatcher#include(javax.servlet.ServletRequest, javax.servlet.ServletResponse)}). 
 * 
 *
 **/

public void insertURL(String servletPath) throws JspException {
    if (LOG.isDebugEnabled())
        LOG.debug("Obtaining Tapestry URL for service " + _serviceName + " at " + servletPath);

    ServletRequest request = _pageContext.getRequest();

    RequestDispatcher dispatcher = request.getRequestDispatcher(servletPath);

    if (dispatcher == null)
        throw new JspException(Tapestry.format("URLRetriever.unable-to-find-dispatcher", servletPath));

    request.setAttribute(Tapestry.TAG_SUPPORT_SERVICE_ATTRIBUTE, _serviceName);
    request.setAttribute(Tapestry.TAG_SUPPORT_PARAMETERS_ATTRIBUTE, _serviceParameters);
    request.setAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE, servletPath);

    try {
        _pageContext.getOut().flush();

        dispatcher.include(request, _pageContext.getResponse());
    } catch (IOException ex) {
        throw new JspException(Tapestry.format("URLRetriever.io-exception", servletPath, ex.getMessage()));
    } catch (ServletException ex) {
        throw new JspException(Tapestry.format("URLRetriever.servlet-exception", servletPath, ex.getMessage()));
    } finally {
        request.removeAttribute(Tapestry.TAG_SUPPORT_SERVICE_ATTRIBUTE);
        request.removeAttribute(Tapestry.TAG_SUPPORT_PARAMETERS_ATTRIBUTE);
        request.removeAttribute(Tapestry.TAG_SUPPORT_SERVLET_PATH_ATTRIBUTE);
    }

}