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:uk.co.channele.itres.Documents.java

public void doGet(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher handler;
        IdentityBean userId;/*from   w w w . ja v  a  2s.  c o m*/
        NewsBean newsBean;
        synchronized (this) {
            HttpSession session = rqst.getSession(false);
            if (session != null) {
                userId = (IdentityBean) session.getAttribute("userIdentity");
                if (userId.isRegistered()) {
                    if (session.getAttribute("newsBean") == null) {
                        newsBean = new NewsBean();
                        session.setAttribute("newsBean", newsBean);
                    } else {
                        newsBean = (NewsBean) session.getAttribute("newsBean");
                    }
                    newsBean.setUserId(userId.getUserName());
                    newsBean.setRemoteHost(rqst.getRemoteHost());
                    newsBean.setEditable(true);
                    handler = context.getRequestDispatcher("/notices.jsp");
                } else {
                    handler = context.getRequestDispatcher("/register.jsp");
                }
            } else {
                handler = context.getRequestDispatcher("/index.jsp");
            }
            handler.include(rqst, resp);
        } // end sync
    }

From source file:org.apache.struts.action.RequestProcessor.java

/**
 * <p>Do an include of specified URI using a <code>RequestDispatcher</code>.
 * This method is used by all internal method needing to do an
 * include.</p>/* w  ww  .ja  va  2  s  .c  o m*/
 *
 * @param uri      Context-relative URI to include
 * @param request  Current page request
 * @param response Current page response
 * @throws IOException      if an input/output error occurs
 * @throws ServletException if a servlet exception occurs
 * @since Struts 1.1
 */
protected void doInclude(String uri, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    RequestDispatcher rd = getServletContext().getRequestDispatcher(uri);

    if (rd == null) {
        response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,
                getInternal().getMessage("requestDispatcher", uri));

        return;
    }

    rd.include(request, response);
}

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

/**
 * parse SSI line and include resource (<!--#include virtual="file.html" -->)
 *///w w w . j a  va 2 s .  com
protected void parseSSI(final byte[] in, HttpServletRequest request, HttpServletResponse response)
        throws IOException, ServletException {
    ByteBuffer buffer = new ByteBuffer(in);
    OutputStream out = response.getOutputStream();
    final byte[] inctxt = "<!--#include virtual=\"".getBytes();
    int offset = 0;
    int p = buffer.indexOf(inctxt, offset);
    int end;
    while (p >= 0 && (end = buffer.indexOf("-->".getBytes(), p + 24)) > 0) { // min length 24; <!--#include virtual="a"
        out.write(in, offset, p - offset);
        out.flush();
        // find right end quote
        final int rightquote = buffer.indexOf("\"".getBytes(), p + 23);
        if (rightquote > 0 && rightquote < end) {
            final String path = buffer.toString(p + 22, rightquote - p - 22);
            RequestDispatcher dispatcher = request.getRequestDispatcher(path);
            try {
                dispatcher.include(request, response);
            } catch (IOException ex) {
                if (path.indexOf("yacysearch") < 0)
                    ConcurrentLog.warn("FILEHANDLER", "YaCyDefaultServlet: parseSSI dispatcher problem - "
                            + ex.getMessage() + ": " + path);
                // this is probably a time-out; it may occur during search requests; for search requests we consider that normal
            }
        } else {
            ConcurrentLog.warn("FILEHANDLER", "YaCyDefaultServlet: parseSSI closing quote missing "
                    + buffer.toString(p, end - p) + " in " + request.getPathInfo());
        }
        offset = end + 3; // after "-->"
        p = buffer.indexOf(inctxt, offset);
    }
    out.write(in, offset, in.length - offset);
    out.close();
    buffer.close();
}

From source file:com.liferay.portlet.InvokerPortletImpl.java

protected void invoke(LiferayPortletRequest portletRequest, LiferayPortletResponse portletResponse,
        String lifecycle, List<? extends PortletFilter> filters) throws IOException, PortletException {

    FilterChain filterChain = new FilterChainImpl(_portlet, filters);

    if (_portletConfigImpl.isWARFile()) {
        String invokerPortletName = _portletConfigImpl.getInitParameter(INIT_INVOKER_PORTLET_NAME);

        if (invokerPortletName == null) {
            invokerPortletName = _portletConfigImpl.getPortletName();
        }//from  ww  w . j  av a 2  s  .  c o  m

        String path = StringPool.SLASH + invokerPortletName + "/invoke";

        RequestDispatcher requestDispatcher = _portletContextImpl.getServletContext()
                .getRequestDispatcher(path);

        HttpServletRequest request = portletRequest.getHttpServletRequest();
        HttpServletResponse response = portletResponse.getHttpServletResponse();

        request.setAttribute(JavaConstants.JAVAX_PORTLET_PORTLET, _portlet);
        request.setAttribute(PortletRequest.LIFECYCLE_PHASE, lifecycle);
        request.setAttribute(PortletServlet.PORTLET_SERVLET_FILTER_CHAIN, filterChain);

        try {

            // Resource phase must be a forward because includes do not
            // allow you to specify the content type or headers

            if (lifecycle.equals(PortletRequest.RESOURCE_PHASE)) {
                requestDispatcher.forward(request, response);
            } else {
                requestDispatcher.include(request, response);
            }
        } catch (ServletException se) {
            Throwable cause = se.getRootCause();

            if (cause instanceof PortletException) {
                throw (PortletException) cause;
            }

            throw new PortletException(cause);
        }
    } else {
        PortletFilterUtil.doFilter(portletRequest, portletResponse, lifecycle, filterChain);
    }

    portletResponse.transferMarkupHeadElements();

    Map<String, String[]> properties = portletResponse.getProperties();

    if ((properties != null) && (properties.size() > 0)) {
        if (_expCache != null) {
            String[] expCache = properties.get(RenderResponse.EXPIRATION_CACHE);

            if ((expCache != null) && (expCache.length > 0) && (expCache[0] != null)) {

                _expCache = new Integer(GetterUtil.getInteger(expCache[0]));
            }
        }
    }
}

From source file:uk.co.channele.itres.Documents.java

public void doPost(HttpServletRequest rqst, HttpServletResponse resp) throws ServletException, IOException {
        RequestDispatcher handler;
        DiskFileItemFactory fileFactory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(fileFactory);
        if (ServletFileUpload.isMultipartContent(rqst)) {
            log.debug("Documents, doPost: got multipart content");
            try {
                List fileList = fileUpload.parseRequest(rqst);
                Iterator i = fileList.iterator();
                while (i.hasNext()) {
                    log.debug("Documents, doPost: iterator has items");
                    FileItem item = (FileItem) i.next();
                    if (!item.isFormField()) {
                        log.debug("Documents, doPost: filename=" + item.getName());
                        File uploadedFile = new File("/home/tomcat/itres_static/docs/" + item.getName());
                        item.write(uploadedFile);
                    } else {
                        log.debug("Documents, doPost: form field=" + item.getFieldName());
                    }//from  w  w w .  j  a va  2 s. c o m
                }
            } catch (FileUploadException fuex) {
                log.error("Documents, doPost:", fuex);
            } catch (Exception ex) {
                log.error("Documents, doPost:", ex);
            }
        } else {
            log.debug("Documents, doPost: NOT multipart content");
        }
        handler = context.getRequestDispatcher("/docs.jsp");
        handler.include(rqst, resp);
    }

From source file:net.yacy.http.servlets.YaCyDefaultServlet.java

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String pathInfo;//from   w  w w.  j  av  a2s  . c  om
    Enumeration<String> reqRanges = null;
    boolean included = request.getAttribute(RequestDispatcher.INCLUDE_REQUEST_URI) != null;
    if (included) {
        pathInfo = (String) request.getAttribute(RequestDispatcher.INCLUDE_PATH_INFO);
        if (pathInfo == null) {
            pathInfo = request.getPathInfo();
        }
    } else {
        pathInfo = request.getPathInfo();

        // Is this a Range request?
        reqRanges = request.getHeaders(HeaderFramework.RANGE);
        if (!hasDefinedRange(reqRanges)) {
            reqRanges = null;
        }
    }

    String pathInContext = pathInfo == null ? "/" : pathInfo; // this is the path of the resource in _resourceBase (= path within htroot respective htDocs)
    boolean endsWithSlash = pathInContext.endsWith(URIUtil.SLASH);

    // Find the resource 
    Resource resource = null;

    try {

        // Look for a class resource
        boolean hasClass = false;
        if (reqRanges == null && !endsWithSlash) {
            final int p = pathInContext.lastIndexOf('.');
            if (p >= 0) {
                String pathofClass = pathInContext.substring(0, p) + ".class";
                Resource classresource = _resourceBase.addPath(pathofClass);
                // Does a class resource exist?
                if (classresource != null && classresource.exists() && !classresource.isDirectory()) {
                    hasClass = true;
                }
            }
        }

        // find resource
        resource = getResource(pathInContext);

        if (!hasClass && (resource == null || !resource.exists()) && !pathInContext.contains("..")) {
            // try to get this in the alternative htDocsPath
            resource = Resource.newResource(new File(_htDocsPath, pathInContext));
        }

        if (ConcurrentLog.isFine("FILEHANDLER")) {
            ConcurrentLog.fine("FILEHANDLER",
                    "YaCyDefaultServlet: uri=" + request.getRequestURI() + " resource=" + resource);
        }

        // Handle resource
        if (!hasClass && (resource == null || !resource.exists())) {
            if (included) {
                throw new FileNotFoundException("!" + pathInContext);
            }
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
        } else if (!resource.isDirectory()) {
            if (endsWithSlash && pathInContext.length() > 1) {
                String q = request.getQueryString();
                pathInContext = pathInContext.substring(0, pathInContext.length() - 1);
                if (q != null && q.length() != 0) {
                    pathInContext += "?" + q;
                }
                response.sendRedirect(response
                        .encodeRedirectURL(URIUtil.addPaths(_servletContext.getContextPath(), pathInContext)));
            } else {
                if (hasClass) { // this is a YaCy servlet, handle the template
                    handleTemplate(pathInfo, request, response);
                } else {
                    if (included || passConditionalHeaders(request, response, resource)) {
                        sendData(request, response, included, resource, reqRanges);
                    }
                }
            }
        } else { // resource is directory
            String welcome;

            if (!endsWithSlash) {
                StringBuffer buf = request.getRequestURL();
                synchronized (buf) {
                    int param = buf.lastIndexOf(";");
                    if (param < 0) {
                        buf.append('/');
                    } else {
                        buf.insert(param, '/');
                    }
                    String q = request.getQueryString();
                    if (q != null && q.length() != 0) {
                        buf.append('?');
                        buf.append(q);
                    }
                    response.setContentLength(0);
                    response.sendRedirect(response.encodeRedirectURL(buf.toString()));
                }
            } // else look for a welcome file
            else if (null != (welcome = getWelcomeFile(pathInContext))) {
                ConcurrentLog.fine("FILEHANDLER", "welcome={}" + welcome);

                // Forward to the index
                RequestDispatcher dispatcher = request.getRequestDispatcher(welcome);
                if (dispatcher != null) {
                    if (included) {
                        dispatcher.include(request, response);
                    } else {
                        dispatcher.forward(request, response);
                    }
                }
            } else {
                if (included || passConditionalHeaders(request, response, resource)) {
                    sendDirectory(request, response, resource, pathInContext);
                }
            }
        }
    } catch (IllegalArgumentException e) {
        ConcurrentLog.logException(e);
        if (!response.isCommitted()) {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.getMessage());
        }
    } finally {
        if (resource != null) {
            resource.close();
        }
    }
}

From source file:org.jahia.services.render.webflow.WebflowDispatcherScript.java

/**
 * Execute the script and return the result as a string
 *
 * @param resource resource to display// w  w  w  . ja v  a2 s . c  om
 * @param context
 * @return the rendered resource
 * @throws org.jahia.services.render.RenderException
 *
 */
public String execute(Resource resource, RenderContext context) throws RenderException {
    final View view = getView();
    if (view == null) {
        throw new RenderException("View not found for : " + resource);
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("View '" + view + "' resolved for resource: " + resource);
        }
    }

    String identifier;
    try {
        identifier = resource.getNode().getIdentifier();
    } catch (RepositoryException e) {
        throw new RenderException(e);
    }
    String identifierNoDashes = StringUtils.replace(identifier, "-", "_");
    if (!view.getKey().equals("default")) {
        identifierNoDashes += "__" + view.getKey();
    }

    HttpServletRequest request;
    HttpServletResponse response = context.getResponse();

    @SuppressWarnings("unchecked")
    final Map<String, List<String>> parameters = (Map<String, List<String>>) context.getRequest()
            .getAttribute("actionParameters");

    if (xssFilteringEnabled && parameters != null) {
        final Map<String, String[]> m = Maps.transformEntries(parameters,
                new Maps.EntryTransformer<String, List<String>, String[]>() {
                    @Override
                    public String[] transformEntry(@Nullable String key, @Nullable List<String> value) {
                        return value != null ? value.toArray(new String[value.size()]) : null;
                    }
                });
        request = new WebflowHttpServletRequestWrapper(context.getRequest(), m, identifierNoDashes);
    } else {
        request = new WebflowHttpServletRequestWrapper(context.getRequest(),
                new HashMap<>(context.getRequest().getParameterMap()), identifierNoDashes);
    }

    String s = (String) request.getSession().getAttribute("webflowResponse" + identifierNoDashes);
    if (s != null) {
        request.getSession().removeAttribute("webflowResponse" + identifierNoDashes);
        return s;
    }

    // skip aggregation for potentials fragments under the webflow
    boolean aggregationSkippedForWebflow = false;
    if (!AggregateFilter.skipAggregation(context.getRequest())) {
        aggregationSkippedForWebflow = true;
        context.getRequest().setAttribute(AggregateFilter.SKIP_AGGREGATION, true);
    }

    flowPath = MODULE_PREFIX_PATTERN.matcher(view.getPath()).replaceFirst("");

    RequestDispatcher rd = request.getRequestDispatcher("/flow/" + flowPath);

    Object oldModule = request.getAttribute("currentModule");
    request.setAttribute("currentModule", view.getModule());

    if (logger.isDebugEnabled()) {
        dumpRequestAttributes(request);
    }

    StringResponseWrapper responseWrapper = new StringResponseWrapper(response);

    try {
        FlowDefinitionRegistry reg = ((FlowDefinitionRegistry) view.getModule().getContext()
                .getBean("jahiaFlowRegistry"));
        final GenericApplicationContext applicationContext = (GenericApplicationContext) reg
                .getFlowDefinition(flowPath).getApplicationContext();
        applicationContext.setClassLoader(view.getModule().getClassLoader());
        applicationContext.setResourceLoader(new ResourceLoader() {
            @Override
            public org.springframework.core.io.Resource getResource(String location) {
                return applicationContext.getParent().getResource("/" + flowPath + "/" + location);
            }

            @Override
            public ClassLoader getClassLoader() {
                return view.getModule().getClassLoader();
            }
        });

        rd.include(request, responseWrapper);

        String redirect = responseWrapper.getRedirect();
        if (redirect != null && context.getRedirect() == null) {
            // if we have an absolute redirect, set it and move on
            if (redirect.startsWith("http:/") || redirect.startsWith("https://")) {
                context.setRedirect(responseWrapper.getRedirect());
            } else {
                while (redirect != null) {
                    final String qs = StringUtils.substringAfter(responseWrapper.getRedirect(), "?");
                    final Map<String, String[]> params = new HashMap<String, String[]>();
                    if (!StringUtils.isEmpty(qs)) {
                        params.put("webflowexecution" + identifierNoDashes, new String[] { StringUtils
                                .substringAfterLast(qs, "webflowexecution" + identifierNoDashes + "=") });
                    }
                    HttpServletRequestWrapper requestWrapper = new HttpServletRequestWrapper(request) {
                        @Override
                        public String getMethod() {
                            return "GET";
                        }

                        @SuppressWarnings("rawtypes")
                        @Override
                        public Map getParameterMap() {
                            return params;
                        }

                        @Override
                        public String getParameter(String name) {
                            return params.containsKey(name) ? params.get(name)[0] : null;
                        }

                        @Override
                        public Enumeration getParameterNames() {
                            return new Vector(params.keySet()).elements();
                        }

                        @Override
                        public String[] getParameterValues(String name) {
                            return params.get(name);
                        }

                        @Override
                        public Object getAttribute(String name) {
                            if (WebUtils.FORWARD_QUERY_STRING_ATTRIBUTE.equals(name)) {
                                return qs;
                            }
                            return super.getAttribute(name);
                        }

                        @Override
                        public String getQueryString() {
                            return qs;
                        }
                    };
                    rd = requestWrapper.getRequestDispatcher("/flow/" + flowPath + "?" + qs);
                    responseWrapper = new StringResponseWrapper(response);
                    rd.include(requestWrapper, responseWrapper);

                    String oldRedirect = redirect;
                    redirect = responseWrapper.getRedirect();
                    if (redirect != null) {
                        // if we have an absolute redirect, exit the loop
                        if (redirect.startsWith("http://") || redirect.startsWith("https://")) {
                            context.setRedirect(redirect);
                            break;
                        }
                    } else if (request.getMethod().equals("POST")) {
                        // set the redirect to the last non-null one
                        request.getSession().setAttribute("webflowResponse" + identifierNoDashes,
                                responseWrapper.getString());
                        context.setRedirect(oldRedirect);
                    }
                }
            }
        }
    } catch (ServletException e) {
        throw new RenderException(e.getRootCause() != null ? e.getRootCause() : e);
    } catch (IOException e) {
        throw new RenderException(e);
    } finally {
        request.setAttribute("currentModule", oldModule);
    }
    try {
        if (aggregationSkippedForWebflow) {
            request.removeAttribute(AggregateFilter.SKIP_AGGREGATION);
        }
        return responseWrapper.getString();
    } catch (IOException e) {
        throw new RenderException(e);
    }
}

From source file:org.apache.struts2.dispatcher.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./*from  w  w  w . j a v a2  s.c o  m*/
 */
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();
        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);
            Map<String, Object> parameters = getParameters(invocation);
            Map<String, Object> queryParams = urlHelper.parseQueryString(queryString, true);
            if (queryParams != null && !queryParams.isEmpty())
                parameters.putAll(queryParams);
        }

        // if the view doesn't exist, let's do a 404
        if (dispatcher == null) {
            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:it.classhidra.core.controller.bsController.java

public static void execRedirect(i_stream currentStream, redirects currentStreamRedirect, String id_action,
        ServletContext servletContext, HttpServletRequest request, HttpServletResponse response)
        throws bsControllerException, ServletException, UnavailableException {
    if (currentStream == null || currentStreamRedirect == null)
        return;//  w  w w  . j a  v  a  2 s  .c  o m
    currentStream.onPreRedirect(currentStreamRedirect, id_action);
    RequestDispatcher rd = currentStream.redirect(servletContext, currentStreamRedirect, id_action);
    currentStream.onPostRedirect(rd);

    if (rd == null)
        throw new bsControllerException("Controller generic redirect error. Stream: ["
                + currentStream.get_infostream().getName() + "] ", request, iStub.log_ERROR);
    else {
        try {

            String id_rtype = (String) request.getAttribute(CONST_ID_REQUEST_TYPE);
            if (id_rtype == null)
                id_rtype = CONST_REQUEST_TYPE_FORWARD;

            if (id_rtype.equals(CONST_REQUEST_TYPE_FORWARD)) {
                if (!response.isCommitted())
                    rd.forward(request, response);
                else
                    rd.include(request, response);
            } else {
                rd.include(request, response);
            }

        } catch (Exception e) {
            throw new bsControllerException("Controller generic redirect error. Action: ["
                    + currentStream.get_infostream().getName() + "] ->" + e.toString(), request,
                    iStub.log_ERROR);
        }
    }

}