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.adobe.cq.wcm.core.components.models.form.impl.v1.OptionsImpl.java

@SuppressWarnings("unchecked")
private void populateOptionItemsFromDatasource() {
    if (StringUtils.isBlank(datasourceRT)) {
        return;//from   w ww  . ja va 2  s .c o m
    }
    // build the options by running the datasource code (the list is set as a request attribute)
    RequestDispatcherOptions opts = new RequestDispatcherOptions();
    opts.setForceResourceType(datasourceRT);
    RequestDispatcher dispatcher = request.getRequestDispatcher(resource, opts);
    try {
        if (dispatcher != null) {
            dispatcher.include(request, response);
        } else {
            LOGGER.error("Failed to include the datasource at " + datasourceRT);
        }
    } catch (Exception e) {
        LOGGER.error("Failed to include the datasource at " + datasourceRT, e);
    }

    // retrieve the datasource from the request and adapt it to form options
    SimpleDataSource dataSource = (SimpleDataSource) request.getAttribute(DataSource.class.getName());
    if (dataSource != null) {
        Iterator<Resource> itemIterator = dataSource.iterator();
        if (itemIterator != null) {
            while (itemIterator.hasNext()) {
                Resource item = itemIterator.next();
                OptionItem optionItem = item.adaptTo(OptionItem.class);
                if (optionItem != null
                        && (optionItem.isDisabled() || StringUtils.isNotBlank(optionItem.getValue()))) {
                    optionItems.add(optionItem);
                }
            }
        }
    }
}

From source file:org.jboss.dashboard.ui.controller.responses.ShowPopupPanelPage.java

/**
 * Executes the response. It typically will be one of the response types
 * that are provided in the org.jboss.dashboard.ui.controller.responses package.
 *
 * @param cmdReq Object encapsulating the request information.
 * @return boolean if the execution has been successfuly executed, false otherwise.
 *//*from   ww  w. j a  v  a  2s . c  om*/
public boolean execute(CommandRequest cmdReq) throws Exception {
    Panel panel = getPanel();
    if (log.isDebugEnabled())
        log.debug("ShowPopupPanelPage: " + panel.getFullDescription());
    cmdReq.getResponseObject().setHeader("Content-Encoding", HTTPSettings.lookup().getEncoding());
    cmdReq.getResponseObject().setContentType("text/html;charset=" + HTTPSettings.lookup().getEncoding());
    cmdReq.getRequestObject().setAttribute(Parameters.RENDER_PANEL, panel);
    SessionManager.setCurrentPanel(panel);
    RequestDispatcher rd = cmdReq.getRequestObject().getRequestDispatcher(jsp);
    RequestDispatcher rd1 = cmdReq.getRequestObject().getRequestDispatcher(commonRefreshPanelsPage);
    panel.getProvider().getDriver().fireBeforeRenderPanel(panel, cmdReq.getRequestObject(),
            cmdReq.getResponseObject());
    rd.include(cmdReq.getRequestObject(), cmdReq.getResponseObject());
    rd1.include(cmdReq.getRequestObject(), cmdReq.getResponseObject());
    panel.getProvider().getDriver().fireAfterRenderPanel(panel, cmdReq.getRequestObject(),
            cmdReq.getResponseObject());
    return true;
}

From source file:org.openestate.is24.restapi.webapp.VerificationServlet.java

/**
 * Create a verification request and show a page with the verification link.
 *
 * @param req incoming GET request/* w  ww  .ja  v  a  2 s .  com*/
 * @param resp outgoing response
 * @throws IOException
 * @throws ServletException
 */
protected void doVerificationRequest(HttpServletRequest req, HttpServletResponse resp)
        throws IOException, ServletException {
    Verification verification = null;
    try {
        verification = this.getWebserviceVerification(req);
    } catch (OAuthException ex) {
        throw new IOExceptionWithCause("Can't fetch verification!", ex);
    }

    // store verification informations
    this.storeVerification(verification);

    // put verification informations into request attributes
    req.setAttribute("url", verification.verificationUrl);
    req.setAttribute("token", verification.requestToken);
    req.setAttribute("secret", verification.requestTokenSecret);

    // show JSP view
    resp.setCharacterEncoding("UTF-8");
    RequestDispatcher d = req.getRequestDispatcher("/WEB-INF/views/verification-request.jsp");
    d.include(req, resp);
}

From source file:net.jforum.core.tags.ImportFileTag.java

/**
 * @see javax.servlet.jsp.tagext.SimpleTagSupport#doTag()
 *//*  www .  j  av  a  2 s. co m*/
@Override
public void doTag() throws JspException, IOException {
    // check the URL
    if (StringUtils.isEmpty(url))
        throw new NullAttributeException("import", "url");

    String jsp = this.getFile(url);

    ServletRequest request = this.request();
    ServletResponse respose = this.response();
    HttpSession session = ((HttpServletRequest) request).getSession();
    ServletContext servletContext = session.getServletContext();

    String jspPath = servletContext.getRealPath(jsp);
    File jspFile = new File(jspPath);
    if (!jspFile.exists())
        return;

    respose.flushBuffer();
    RequestDispatcher rd = this.pageContext().getRequest().getRequestDispatcher(jsp);
    try {
        // include the resource, using our custom wrapper
        ImportResponseWrapper irw = new ImportResponseWrapper((HttpServletResponse) respose);
        irw.setCharacterEncoding(charEncoding);
        rd.include(request, irw);
        // disallow inappropriate response codes per JSTL spec
        if (irw.getStatus() < 200 || irw.getStatus() > 299) {
            throw new JspTagException(irw.getStatus() + " " + jsp);
        }

        // recover the response String from our wrapper
        pageContext().getOut().print(irw.getString());
    } catch (ServletException e) {
        e.printStackTrace();
    }
}

From source file:Servlets.ServletUsuario.java

private void cargaUsuario(HttpServletRequest request, HttpServletResponse response)
        throws FileUploadException, Exception {
    FileItemFactory file_factory = new DiskFileItemFactory();
    ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
    List items = servlet_up.parseRequest(request);
    String urlImg = "";
    Hashtable datosUsuario = new Hashtable();
    HttpSession valida = null;// w ww  .  jav  a  2 s.  co  m
    for (int i = 0; i < items.size(); i++) {
        FileItem item = (FileItem) items.get(i);
        if (!item.isFormField()) {
            urlImg = item.getName();
            if (!urlImg.equals("")) {
                String dir = getServletContext().getRealPath("/");
                String dir2 = dir.replaceAll("web", "img");
                String dir3 = dir2.replaceAll("build", "web");
                dir3 = dir3.concat("imgUsuarios/");
                File fileFoto = new File(dir3, item.getName());
                item.write(fileFoto);
            }
        } else {
            datosUsuario.put(item.getFieldName(), item.getString());
        }
    }
    String adm = (String) datosUsuario.get("administrador");
    String mod = (String) datosUsuario.get("Modifica");
    boolean esAdm = false;
    if (adm != null) {
        esAdm = true;
    }
    if (urlImg.equals("")) {
        urlImg = (String) datosUsuario.get("imgdefecto");
    }
    user = new Usuario(0, (String) datosUsuario.get("nombre"), (String) datosUsuario.get("apellido"),
            Integer.parseInt((String) datosUsuario.get("dni")), esAdm, (String) datosUsuario.get("user"),
            (String) datosUsuario.get("pass"), (String) datosUsuario.get("email"),
            (String) datosUsuario.get("telefono"), urlImg);
    if (mod == null) {
        RequestDispatcher rd = getServletContext().getRequestDispatcher(
                "/ServletValidaUser?user=" + user.getUser() + "&email=" + user.getEmail());
        rd.include(request, response);
        valida = request.getSession(true);
        if (valida.getAttribute("usuarioValid") == null) {
            try {
                ctrlUsuario.registraUsuario(user);
            } catch (SQLException ex) {
                Logger.getLogger(ServletRegistro.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            RequestDispatcher volver = request
                    .getRequestDispatcher("/abmUsuario.jsp?errorUser='El nombre de usuario o mail ya existen'");
            volver.forward(request, response);
        }
    } else {
        user.setId(Integer.parseInt(mod));
        ctrlUsuario.modificarUsuario(user);
    }
    //valida.invalidate();
    Thread.sleep(2000);
    RequestDispatcher volver = request.getRequestDispatcher("/abmUsuario.jsp");
    volver.forward(request, response);
}

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

/**
 * <p>Attempt to give good information when the response has already been
 * committed when the exception was thrown. This happens often when Tiles
 * is used. Base implementation will see if the INCLUDE_PATH property has
 * been set, or if not, it will attempt to use the same path to which
 * control would have been forwarded.</p>
 *
 * @param ex            The exception to handle
 * @param config        The ExceptionConfig we are processing
 * @param mapping       The ActionMapping we are processing
 * @param formInstance  The ActionForm we are processing
 * @param request       The servlet request we are processing
 * @param response      The servlet response we are creating
 * @param actionForward The ActionForward we are processing
 * @since Struts 1.3//from ww  w  .j  av a 2s  .co  m
 */
protected void handleCommittedResponse(Exception ex, ExceptionConfig config, ActionMapping mapping,
        ActionForm formInstance, HttpServletRequest request, HttpServletResponse response,
        ActionForward actionForward) {
    String includePath = determineIncludePath(config, actionForward);

    if (includePath != null) {
        if (includePath.startsWith("/")) {
            LOG.debug("response committed, " + "but attempt to include results " + "of actionForward path");

            RequestDispatcher requestDispatcher = request.getRequestDispatcher(includePath);

            try {
                requestDispatcher.include(request, response);

                return;
            } catch (IOException e) {
                LOG.error("IOException when trying to include " + "the error page path " + includePath, e);
            } catch (ServletException e) {
                LOG.error("ServletException when trying to include " + "the error page path " + includePath, e);
            }
        } else {
            LOG.warn("Suspicious includePath doesn't seem likely to work, " + "so skipping it: " + includePath
                    + "; expected path to start with '/'");
        }
    }

    LOG.debug("Include not available or failed; " + "try writing to the response directly.");

    try {
        response.getWriter().println("Unexpected error: " + ex);
        response.getWriter().println("<!-- ");
        ex.printStackTrace(response.getWriter());
        response.getWriter().println("-->");
    } catch (IOException e) {
        LOG.error("Error giving minimal information about exception", e);
        LOG.error("Original exception: ", ex);
    }
}

From source file:org.openestate.is24.restapi.webapp.VerificationServlet.java

/**
 * Creates access credentials after the verification was passed.
 * <p>/*from w  w  w  . j av a  2  s  . co m*/
 * The generated access token and secret is shown to the user by default.
 *
 * @param state the state of verification, that was received as request
 *        parameter by the webservice
 *
 * @param token the verification token, that was received as request parameter
 *        by the webservice
 *
 * @param verifier the verification code, that was received as request
 *        parameter by the webservice
 *
 * @param req incoming GET request
 * @param resp outgoing response
 * @throws IOException
 * @throws ServletException
 */
protected void doVerificationResponse(String state, String token, String verifier, HttpServletRequest req,
        HttpServletResponse resp) throws IOException, ServletException {
    try {
        if (!"authorized".equalsIgnoreCase(state)) {
            req.setAttribute("authorized", false);
        } else {
            req.setAttribute("authorized", true);

            String secret = this.fetchVerificationSecret(token);
            if (token == null || secret == null) {
                req.setAttribute("valid", false);
            } else {
                Authorization authorization = null;
                try {
                    authorization = getWebserviceAuthorization(token, secret, verifier, req);
                } catch (OAuthException ex) {
                    throw new IOExceptionWithCause("Can't fetch authorization!", ex);
                }
                req.setAttribute("valid", true);
                req.setAttribute("token", authorization.accessToken);
                req.setAttribute("secret", authorization.accessTokenSecret);
            }
        }

        // show JSP view
        resp.setCharacterEncoding("UTF-8");
        RequestDispatcher dispatcher = req.getRequestDispatcher("/WEB-INF/views/verification-response.jsp");
        dispatcher.include(req, resp);
    } finally {
        this.removeVerificationSecret(token);
    }
}

From source file:de.jwic.renderer.jsp.JspRenderer.java

public void renderControl(Control control, RenderContext context) {

    if (log.isDebugEnabled()) {
        log.debug("Rendering control '" + control.getControlID() + "' with template '"
                + control.getTemplateName() + "'");
    }/*from  ww  w  .  j  a va 2s  . c o m*/

    String ctrlDivID = "ctrl_" + control.getControlID();//.replace('.', '_');
    PrintWriter writer = context.getWriter();
    if (!control.isVisible()) {
        writer.print("<span id=\"" + ctrlDivID + "\">");
        writer.print("</span>");
        return;
    }

    HttpServletRequest request = context.getRequest();
    request.setAttribute("control", control);
    request.setAttribute("jwic",
            new JWicTools(control.getSessionContext().getLocale(), control.getSessionContext().getTimeZone()));
    if (control instanceof IControlContainer) {
        request.setAttribute("insert", new ChildRenderer((IControlContainer) control, context));
    }

    RequestDispatcher dispatcher = context.getRequest()
            .getRequestDispatcher("/WEB-INF/jwic/jsp/" + control.getTemplateName() + ".jsp");
    try {
        HttpServletResponseFacade res = new HttpServletResponseFacade(context.getResponse(),
                context.getWriter());
        writer.print("<span><span id=\"" + ctrlDivID + "\">");
        dispatcher.include(context.getRequest(), res);
        writer.print("</span></span>");

    } catch (Exception e) {
        log.error("Error including jsp page", e);
        context.getWriter().write("Error rendering Control (" + e + ")");
    }

}

From source file:org.debux.webmotion.server.WebMotionServer.java

/**
 * Static resources management//www  . j  a v a 2s .c  o m
 */
protected void doResource(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    // Suppress the static in path
    HttpServletRequest requestWrapper = new HttpServletRequestWrapper(request) {
        @Override
        public String getServletPath() {
            String servletPath = super.getServletPath();
            if (servletPath != null) {
                return servletPath.replaceFirst(PATH_STATIC, "");
            }
            return null;
        }

        @Override
        public String getPathInfo() {
            String pathInfo = super.getPathInfo();
            if (pathInfo != null) {
                return pathInfo.replaceFirst(PATH_STATIC, "");
            }
            return null;
        }

        @Override
        public String getRequestURI() {
            String requestURI = super.getRequestURI();
            if (requestURI != null) {
                return requestURI.replaceFirst(PATH_STATIC, "");
            }
            return null;
        }
    };

    // Dispatch on default servlet
    ServletContext servletContext = request.getServletContext();
    RequestDispatcher dispatcher = servletContext.getNamedDispatcher("default");

    DispatcherType dispatcherType = request.getDispatcherType();
    if (dispatcherType == DispatcherType.INCLUDE) {
        dispatcher.include(requestWrapper, response);
    } else {
        dispatcher.forward(requestWrapper, response);
    }
}

From source file:org.apache.sling.scripting.sightly.impl.engine.extension.ResourceRuntimeExtension.java

private void includeResource(final Bindings bindings, PrintWriter out, Resource includeRes,
        String dispatcherOptions, String resourceType) {
    if (includeRes == null) {
        throw new SightlyException("Resource cannot be null");
    } else {// www.  ja  va 2s  .c  o  m
        SlingHttpServletResponse customResponse = new PrintWriterResponseWrapper(out,
                BindingsUtils.getResponse(bindings));
        SlingHttpServletRequest request = BindingsUtils.getRequest(bindings);
        RequestDispatcherOptions opts = new RequestDispatcherOptions(dispatcherOptions);
        if (StringUtils.isNotEmpty(resourceType)) {
            opts.setForceResourceType(resourceType);
        }
        RequestDispatcher dispatcher = request.getRequestDispatcher(includeRes, opts);
        try {
            if (dispatcher != null) {
                dispatcher.include(request, customResponse);
            } else {
                throw new SightlyException("Failed to include resource " + includeRes.getPath());
            }
        } catch (Exception e) {
            throw new SightlyException("Failed to include resource " + includeRes.getPath(), e);
        }
    }
}