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.apache.tiles.servlet.context.ServletTilesRequestContext.java

/** {@inheritDoc} */
public void include(String path) throws IOException {
    RequestDispatcher rd = request.getRequestDispatcher(path);
    try {/*from w  w  w .  j a v a2 s  .c  om*/
        rd.include(request, response);
    } catch (ServletException ex) {
        LOG.error("Servlet Exception while including path", ex);
        throw new IOException("Error including path '" + path + "'. " + ex.getMessage());
    }
}

From source file:org.apache.struts.tiles.commands.TilesPreProcessor.java

/**
 * <p>Do an include of specified URI using a <code>RequestDispatcher</code>.</p>
 *
 * @param context a chain servlet/web context
 * @param uri Context-relative URI to include
 *///from  w  ww.  j a va 2s  .c o  m
protected void doInclude(ServletActionContext context, String uri) throws IOException, ServletException {

    RequestDispatcher rd = getRequiredDispatcher(context, uri);

    if (rd != null) {
        rd.include(context.getRequest(), context.getResponse());
    }
}

From source file:com.logiclander.jaasmine.authentication.http.SimpleLogoutServlet.java

/**
 * Logs out the Subject associated with the user.
 *
 * After the logout is done, the request is dispatched to a Servlet or JSP
 * specified by the {@code postLogoutProcessorName} init-param.  If the
 * param was not specified, a {@code text/plain} message will be written
 * to the response./* w  w  w  .  j av  a  2 s. c  om*/
 *
 * This method is not idempotent.  If a request is made successfully once,
 * the user will be logged out.  Subsequent requests without a login will
 * cause an HTTP 403 - Forbidden to be returned.
 *
 * @param req the HttpServletRequest
 * @param resp the HttpServletResponse
 * @throws ServletException if a ServletException is thrown after the
 * request is dispatched to the post logout processor.
 * @throws IOException if an I/O error occurs.
 */
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    HttpSession sess = req.getSession();
    Subject subj = (Subject) sess.getAttribute(AuthenticationService.SUBJECT_KEY);

    if (subj == null) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // Log out the Subject
    AuthenticationService as = new SimpleAuthenticationService(appName);
    as.logout(subj);

    // Invalidate the session
    sess.invalidate();

    resp.setStatus(HttpServletResponse.SC_OK);
    RequestDispatcher rd = getServletContext().getNamedDispatcher(postLogoutProcessorName);

    if (rd != null) {
        resp.setContentType("text/html");
        rd.include(req, resp);
    } else {
        sendPlainTextResponse(resp);
    }

}

From source file:org.springframework.extensions.webscripts.servlet.mvc.ResourceController.java

public void commitResponse(final String path, final Resource resource, final HttpServletRequest request,
        final HttpServletResponse response) throws IOException, ServletException {
    // determine properties of the resource being served back
    final URLConnection resourceConn = resource.getURL().openConnection();
    applyHeaders(path, response, resourceConn.getContentLength(), resourceConn.getLastModified());

    // stream back to response
    RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/" + path);
    rd.include(request, response);
}

From source file:in.edu.ssn.servlet.RegisterServlet.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*  w  ww  .j  a  v a 2 s .co m*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    try {

        String email = request.getParameter("email");
        String password = request.getParameter("password");
        //    System.out.println(numplate+mobileno);

        Client client;
        client = ClientBuilder.newClient();
        WebTarget target = client
                .target("https://api.idolondemand.com/1/api/sync/adduser/v1?store=myparkinglot&email=" + email
                        + "&password=" + password + "&apikey=fa64dd8c-6193-47fd-a4ba-052939805fa4");

        String response1 = target.request().get(String.class);
        org.json.JSONObject jsonObject = new org.json.JSONObject(response1);
        //JSONArray newJSON = jsonObject.getJSONArray("documents");
        String c1n = new String();
        //jsonObject = newJSON.getJSONObject(0);

        c1n = jsonObject.getString("message");
        System.out.println(c1n);
        System.out.println(response);
        if (c1n != null)

        {
            RequestDispatcher rd = request.getRequestDispatcher("/book.html");
            rd.forward(request, response);
        } else {
            RequestDispatcher rd = request.getRequestDispatcher("/home.html");
            rd.include(request, response);
        }
        /* TODO output your page here. You may use following sample code. 
        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet RegisterServlet</title>");            
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>" + response1 + "</h1>");
        out.println("</body>");
        out.println("</html>");*/

    } finally {
        out.close();
    }
}

From source file:com.cyclopsgroup.waterview.jsp.JspEngine.java

/**
 * @param path Absolute JSP path/* ww  w.  j  a v a  2s . co  m*/
 * @param data Runtime data
 * @param viewContext View context
 * @throws Exception Throw it out
 */
public void renderJsp(String path, RuntimeData data, Context viewContext) throws Exception {
    HttpServletRequest request = (HttpServletRequest) data.getRequestContext().get("request");
    HttpServletResponse response = (HttpServletResponse) data.getRequestContext().get("response");
    ServletContext servletContext = (ServletContext) data.getRequestContext().get("servletContext");
    if (request == null || response == null || servletContext == null) {
        data.getOutput().println("Jsp " + path + " is not rendered correctly with request " + request
                + ", response " + response + ", context " + servletContext);
    }
    request.setAttribute("viewContext", viewContext);
    RequestDispatcher dispatcher = servletContext.getRequestDispatcher(path);
    File jspFile = new File(servletContext.getRealPath(path));
    if (dispatcher == null || !jspFile.isFile()) {
        data.getOutput().println("Jsp " + path + " doesn't exist");
    } else {
        dispatcher.include(request, response);
        response.getWriter().flush();
    }
    request.removeAttribute("viewContext");
}

From source file:org.eclipse.orion.server.authentication.formopenid.servlets.FormOpenIdLoginServlet.java

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

    String pathInfo = req.getPathInfo() == null ? "" : req.getPathInfo(); //$NON-NLS-1$

    if (pathInfo.startsWith("/form")) { //$NON-NLS-1$
        try {//from   w ww  . ja v a2  s.  c o m
            if (FormAuthHelper.performAuthentication(req, resp)) {
                if (req.getParameter(OpenIdHelper.REDIRECT) != null
                        && !req.getParameter(OpenIdHelper.REDIRECT).equals("")) { //$NON-NLS-1$
                    resp.sendRedirect(req.getParameter(OpenIdHelper.REDIRECT));
                } else {
                    resp.flushBuffer();
                }
            } else {
                // redirection from
                // FormAuthenticationService.setNotAuthenticated
                String versionString = req.getHeader("Orion-Version"); //$NON-NLS-1$
                Version version = versionString == null ? null : new Version(versionString);

                // TODO: This is a workaround for calls
                // that does not include the WebEclipse version header
                String xRequestedWith = req.getHeader("X-Requested-With"); //$NON-NLS-1$

                String invalidLoginError = "Invalid user or password";

                if (version == null && !"XMLHttpRequest".equals(xRequestedWith)) { //$NON-NLS-1$
                    RequestDispatcher rd = req.getRequestDispatcher(
                            "/mixlogin?error=" + new String(Base64.encode(invalidLoginError.getBytes()))); //$NON-NLS-1$
                    rd.include(req, resp);
                } else {
                    PrintWriter writer = resp.getWriter();
                    JSONObject jsonError = new JSONObject();
                    try {
                        jsonError.put("error", invalidLoginError); //$NON-NLS-1$
                        writer.print(jsonError);
                        resp.setContentType("application/json"); //$NON-NLS-1$
                    } catch (JSONException e) {/* ignore */
                    }
                    resp.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                }
                resp.flushBuffer();
            }
        } catch (UnsupportedUserStoreException e) {
            LogHelper.log(e);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND, e.getMessage());
        }
        return;
    }

    if (pathInfo.startsWith("/openid")) { //$NON-NLS-1$
        String openid = req.getParameter(OpenIdHelper.OPENID);
        if (openid != null) {
            consumer = OpenIdHelper.redirectToOpenIdProvider(req, resp, consumer);
            return;
        }

        String op_return = req.getParameter(OpenIdHelper.OP_RETURN);
        if (op_return != null) {
            OpenIdHelper.handleOpenIdReturn(req, resp, consumer);
            return;
        }
    }

    String user;
    if ((user = authenticationService.getAuthenticatedUser(req, resp,
            authenticationService.getDefaultAuthenticationProperties())) != null) {
        resp.setStatus(HttpServletResponse.SC_OK);
        try {
            JSONObject array = new JSONObject();
            array.put("login", user); //$NON-NLS-1$
            resp.getWriter().print(array.toString());
        } catch (JSONException e) {
            handleException(resp, "An error occured when creating JSON object for logged in user", e);
        }
        return;
    }
}

From source file:nl.nn.adapterframework.webcontrol.DumpIbisConsole.java

public void copyServletResponse(ZipOutputStream zipOutputStream, HttpServletRequest request,
        HttpServletResponse response, String resource, String destinationFileName, Set resources, Set linkSet,
        String linkFilter) {//w  w w.  j  ava2  s.  c  o  m
    long timeStart = new Date().getTime();
    try {
        IbisServletResponseWrapper ibisHttpServletResponseGrabber = new IbisServletResponseWrapper(response);
        RequestDispatcher requestDispatcher = servletContext.getRequestDispatcher(resource);
        requestDispatcher.include(request, ibisHttpServletResponseGrabber);
        String htmlString = ibisHttpServletResponseGrabber.getStringWriter().toString();

        ZipEntry zipEntry = new ZipEntry(destinationFileName);
        //         if (resourceModificationTime!=0) {
        //            zipEntry.setTime(resourceModificationTime);
        //         }

        zipOutputStream.putNextEntry(zipEntry);

        PrintWriter pw = new PrintWriter(zipOutputStream);
        pw.print(htmlString);
        pw.flush();
        zipOutputStream.closeEntry();

        if (!resource.startsWith("FileViewerServlet")) {
            extractResources(resources, htmlString);
        }
        if (linkSet != null) {
            followLinks(linkSet, htmlString, linkFilter);
        }
    } catch (Exception e) {
        log.error("Error copying servletResponse", e);
    }
    long timeEnd = new Date().getTime();
    log.debug("dumped file [" + destinationFileName + "] in " + (timeEnd - timeStart) + " msec.");
}

From source file:com.adobe.cq.wcm.core.components.internal.models.v1.form.OptionsImpl.java

@SuppressWarnings("unchecked")
private void populateOptionItemsFromDatasource() {
    if (StringUtils.isBlank(datasourceRT)) {
        return;//from   w  w  w.  j av  a  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 itemResource = itemIterator.next();
                OptionItem optionItem = new OptionItemImpl(request, resource, itemResource);
                if ((optionItem.isDisabled() || StringUtils.isNotBlank(optionItem.getValue()))) {
                    optionItems.add(optionItem);
                }
            }
        }
    }
}

From source file:Servlets.ServletRegistro.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
 *
 * @param request servlet request/*from w  w  w.  j  a  v a 2s  .c  o  m*/
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException, FileUploadException, Exception {
    response.setContentType("text/html;charset=UTF-8");
    boolean isMultipart = ServletFileUpload.isMultipartContent(request);
    HttpSession valida = null;
    if (isMultipart) {
        FileItemFactory file_factory = new DiskFileItemFactory();
        ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
        List items = servlet_up.parseRequest(request);
        String urlImg = "";
        Hashtable datosUsuario = new Hashtable();
        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.concat("imgUsuarios/");
                    File fileFoto = new File(dir3, item.getName());
                    item.write(fileFoto);
                }
            } else {
                datosUsuario.put(item.getFieldName(), item.getString());
            }
        }
        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")), false, (String) datosUsuario.get("user"),
                (String) datosUsuario.get("pass"), (String) datosUsuario.get("email"),
                (String) datosUsuario.get("telefono"), urlImg);
        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);
                user = ctrlLogin.validaUsuario(user);
                HttpSession sesion = request.getSession(true);
                sesion.setAttribute("usuarioLog", user);
                RequestDispatcher aux = request.getRequestDispatcher("/principal.jsp");
                aux.forward(request, response);
            } catch (SQLException ex) {
                Logger.getLogger(ServletRegistro.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            valida.invalidate();
        }
    } else {
        String idUsuario = request.getParameter("idUsuario");
        ArrayList<Usuario> list = null;
        boolean flag = false;
        if (idUsuario == null) {
            flag = true;
        } else {
            if (!idUsuario.equals("0")) {
                list = new ArrayList<>();
                list.add(ctrlUsuario.traePorId(Integer.parseInt(idUsuario)));
                flag = true;
            }
            if (flag) {
                list = ctrlUsuario.listarUsuarios();
                String json = new Gson().toJson(list);
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(json);
            }
        }
    }
}