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.util.WebUtils.java

/**
 * Includes the given URL returning the resulting content as a String
 *
 * @param includeUrl The URL to include//  w ww  .ja va2s .co  m
 * @param request The request
 * @param response The response
 * @param model The model
 * @return The content
 */
@SuppressWarnings({ "unchecked", "rawtypes" })
public static IncludedContent includeForUrl(String includeUrl, HttpServletRequest request,
        HttpServletResponse response, Map model) {
    RequestDispatcher dispatcher = request.getRequestDispatcher(includeUrl);
    HttpServletResponse wrapped = WrappedResponseHolder.getWrappedResponse();
    response = wrapped != null ? wrapped : response;

    exposeIncludeRequestAttributes(request);

    Map toRestore = exposeRequestAttributesAndReturnOldValues(request, model);

    try {
        final IncludeResponseWrapper responseWrapper = new IncludeResponseWrapper(response);
        try {
            WrappedResponseHolder.setWrappedResponse(responseWrapper);
            dispatcher.include(request, responseWrapper);
            if (responseWrapper.getRedirectURL() != null) {
                return new IncludedContent(responseWrapper.getRedirectURL());
            }
            return new IncludedContent(responseWrapper.getContentType(), responseWrapper.getContent());
        } finally {
            WrappedResponseHolder.setWrappedResponse(wrapped);
        }
    } catch (Exception e) {
        throw new ControllerExecutionException("Unable to execute include: " + e.getMessage(), e);
    } finally {
        cleanupIncludeRequestAttributes(request, toRestore);
    }
}

From source file:org.jpublish.util.PathDispatcherManager.java

/**
 * This method is damn tricky./*from  w  w  w.  j av a 2  s .  com*/
 * Ask Anthony how we can re-process the input supplied by our
 * new "slave": the Servlet which just proccessed the request ;)
 * <p/>
 * We can therefore to "influence" the output by using Velocity or Actions...
 * todo... check this f@#$ gizmo
 * <p/>
 * BufferedReader br = new BufferedReader( new InputStreamReader(request.getInputStream() ) );
 * String data = br.readLine();
 * ...todo: eat this data
 * if(br !=null) br.close();
 * apparently is working but is weird :)) I hope is not a mistake
 *
 * @param request
 * @param response
 * @param dispatcherName
 * @throws IOException
 * @throws ServletException
 */
public void include(HttpServletRequest request, HttpServletResponse response, String dispatcherName)
        throws IOException, ServletException {

    if (dispatcherName != null) {
        RequestDispatcher rd = siteContext.getServletContext().getNamedDispatcher(dispatcherName);
        rd.include(request, response);
        // unfinished....
    }
}

From source file:org.seasar.s2click.filter.UrlPatternFilter.java

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
        throws IOException, ServletException {

    HttpServletRequest req = HttpServletRequest.class.cast(request);

    String requestUri = req.getRequestURI();
    String context = req.getContextPath();
    String queryString = req.getQueryString();

    String requestPath = requestUri.substring(context.length());
    if (StringUtils.isNotEmpty(queryString)) {
        requestPath = requestPath + "?" + queryString;
    }/*w  w  w  . j av  a  2  s  . co m*/
    if (logger.isDebugEnabled()) {
        logger.debug("UrlRewriteFilter???");
        logger.debug("" + requestPath);
    }

    // ?????????
    if (excludePattern != null) {
        Matcher matcher = excludePattern.matcher(requestPath);
        if (matcher.matches()) {
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "?????UrlRewriteFilter?????");
            }
            chain.doFilter(request, response);
            return;
        }
    }

    // HOT deploy??????ClickApp??
    S2Container container = SingletonS2ContainerFactory.getContainer();

    if (SmartDeployUtil.isHotdeployMode(container) && request.getAttribute(HOTDEPLOY_INIT_KEY) == null) {
        if (logger.isDebugEnabled()) {
            logger.debug("UrlRewriteFilter?Click??????");
        }

        request.setAttribute(HOTDEPLOY_INIT_KEY, "initialize");
        RequestDispatcher dispatcher = request.getRequestDispatcher("/init.htm");
        dispatcher.include(request, response);
    }

    for (UrlRewriteInfo info : UrlPatternManager.getAll()) {
        Matcher matcher = info.pattern.matcher(requestPath);
        if (matcher.matches()) {
            StringBuilder realPath = new StringBuilder();
            realPath.append(info.realPath);
            for (int i = 0; i < info.parameters.length; i++) {
                if (i == 0) {
                    realPath.append("?");
                } else {
                    realPath.append("&");
                }
                realPath.append(info.parameters[i]);
                realPath.append("=");
                realPath.append(matcher.group(i + 1));
            }

            if (logger.isDebugEnabled()) {
                logger.debug(realPath.toString() + "????");
            }

            RequestDispatcher dispatcher = request.getRequestDispatcher(realPath.toString());
            dispatcher.forward(request, response);
            return;
        }
    }

    chain.doFilter(request, response);
}

From source file:classes.newsserv.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./*www  . ja v  a 2 s .  c om*/
 *
 * @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, FileUploadException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();

    // Apache Commons-Fileupload library classes
    DiskFileItemFactory factory = new DiskFileItemFactory();
    ServletFileUpload sfu = new ServletFileUpload(factory);

    if (!ServletFileUpload.isMultipartContent(request)) {
        System.out.println("sorry. No file uploaded");
        return;
    }

    try {// parse request
        List items = sfu.parseRequest(request);
        FileItem title = (FileItem) items.get(0);
        String t = title.getString();
        //System.out.println("t=" + t);
        FileItem news = (FileItem) items.get(1);
        String n = news.getString();

        FileItem date = (FileItem) items.get(2);
        String d = date.getString();

        FileItem time = (FileItem) items.get(3);
        String ti = time.getString();

        FileItem btn = (FileItem) items.get(5);
        String button = btn.getString();

        // get uploaded file
        FileItem file = (FileItem) items.get(4);

        if (button.equals("add")) {
            adminclass x = new adminclass();
            if (x.insertnews(t, n, d, ti, file)) {

                RequestDispatcher regd = request.getRequestDispatcher("news.jsp");
                regd.include(request, response);
            }
        }

        else if (button.equals("Select")) {//System.out.println("aval");
            adminclass x = new adminclass();

            ArrayList al = new ArrayList();
            id = Long.parseLong(request.getParameter("txt_id"));

            al = x.searchnews(id);
            request.setAttribute("data", al);
            // out.println("Record Searched");
            //            id=Long.parseLong(al.get(0).toString());
            //System.out.println(id);
            RequestDispatcher regd = request.getRequestDispatcher("news.jsp");
            regd.include(request, response);
        } else if (button.equals("update")) {
            adminclass x = new adminclass();

            if (x.updatenews(id, t, n, d, ti)) {
                RequestDispatcher regd = request.getRequestDispatcher("news.jsp");
                regd.include(request, response);
            }
        }
    } finally {
        out.close();
    }
}

From source file:com.krawler.esp.servlets.ProfileImageServlet.java

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    // Get the absolute path of the image
    ServletContext sc = getServletContext();
    String uri = req.getRequestURI();
    String servletBase = req.getServletPath();
    if (!StringUtil.isNullOrEmpty(req.getParameter("flag"))) {
        try {//  ww  w . j  ava  2s. co m
            // TODO: Fix hardcoded url
            if (!StringUtil.isNullOrEmpty(req.getParameter("trackid"))) {
                String url = "/remoteapi.jsp?action=100&data={\"iscommit\":true}&trackid="
                        + req.getParameter("trackid");
                RequestDispatcher rd = req.getRequestDispatcher(url);
                rd.include(req, resp);
            }
            String fileName = StorageHandler.GetProfileImgStorePath() + "blankImage.png";
            File file = new File(fileName);
            if (file.exists()) {
                FileInputStream in = new FileInputStream(file);
                OutputStream out = resp.getOutputStream();

                // Copy the contents of the file to the output stream
                byte[] buf = new byte[4096];
                int count = 0;
                while ((count = in.read(buf)) >= 0) {
                    out.write(buf, 0, count);
                }
                in.close();
                out.close();
            }
        } catch (Exception e) {
            logger.warn(e.getMessage(), e);
        }
    } else {
        boolean Companyflag = (req.getParameter("company") != null) ? true : false;
        String imagePath = defaultImgPath;
        String requestedFileName = "";
        if (Companyflag) {
            imagePath = defaultCompanyImgPath;
            String companyId = null;
            try {
                companyId = sessionHandlerImpl.getCompanyid(req);
            } catch (Exception ee) {
                logger.warn(ee.getMessage(), ee);
            }
            if (StringUtil.isNullOrEmpty(companyId)) {
                String domain = URLUtil.getDomainName(req);
                if (!StringUtil.isNullOrEmpty(domain)) {
                    //@@@
                    //                        companyId = sessionHandlerImpl.getCompanyid(domain);
                    requestedFileName = "/original_" + companyId + ".png";
                } else {
                    requestedFileName = "logo.gif";
                }
            } else {
                requestedFileName = "/" + companyId + ".png";
            }
        } else {
            requestedFileName = uri.substring(uri.lastIndexOf(servletBase) + servletBase.length());
        }
        String fileName = null;

        fileName = StorageHandler.GetProfileImgStorePath() + requestedFileName;
        // Get the MIME type of the image
        String mimeType = sc.getMimeType(fileName);
        if (mimeType == null) {
            sc.log("Could not get MIME type of " + fileName);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            return;
        }

        // Set content type
        resp.setContentType(mimeType);

        // Set content size
        File file = new File(fileName);
        if (!file.exists()) {
            if (fileName.contains("_100.")) {
                file = new File(fileName.replaceAll("_100.", "."));
            }
            if (!file.exists()) {
                file = new File(sc.getRealPath(imagePath));
            }
        }

        resp.setContentLength((int) file.length());

        // Open the file and output streams
        FileInputStream in = new FileInputStream(file);
        OutputStream out = resp.getOutputStream();

        // Copy the contents of the file to the output stream
        byte[] buf = new byte[4096];
        int count = 0;
        while ((count = in.read(buf)) >= 0) {
            out.write(buf, 0, count);
        }
        in.close();
        out.close();
    }
}

From source file:org.gwtportlets.portlet.server.WebAppContentDataProvider.java

public void refresh(WebAppContentPortlet.Factory f, PageRequest req) {
    if (f.path == null || f.path.length() == 0) {
        f.html = null;/*from  w  w  w  .j a  va 2  s.  c o m*/
    } else {
        HttpServletRequest servletRequest = req.getServletRequest();
        String path = f.path.startsWith("/") ? f.path : "/" + f.path;
        RequestDispatcher rd = servletRequest.getRequestDispatcher(path);
        BufferedResponse res = new BufferedResponse(req.getServletResponse());
        try {
            rd.include(servletRequest, res);
            res.getWriter().flush();
            f.html = new String(res.toByteArray(), res.getCharacterEncoding());
        } catch (Exception e) {
            log.error("Error including '" + path + "': " + e, e);
            f.html = "Error including '" + path + "'<br>(see server log for details)";
        }
    }
}

From source file:com.openedit.generators.FilterGenerator.java

public void generate(WebPageRequest inContext, Page inPage, Output inOut) throws OpenEditException {
    HttpServletRequest httpRequest = inContext.getRequest();
    HttpServletResponse httpResponse = inContext.getResponse();
    Page page = (Page) inContext.getPageValue("page");

    //load the standard context objects
    httpRequest.setAttribute("context", inContext);
    httpRequest.setAttribute("pages", inContext.getPageStreamer());
    httpRequest.setAttribute("content", inContext.getContentPage());

    /* I commented this out since it conflics with existing JSP pages. Blojsom has its own "page" variable, get stuff from the context
     for (Iterator iter = inContext.getPageMap().entrySet().iterator(); iter.hasNext();)
     {//from w w  w  . j a  v  a 2  s.  co m
     Map.Entry entry = (Map.Entry) iter.next();
     String key = (String) entry.getKey();
     httpRequest.setAttribute(key, inContext.getPageValue(key));
     }
     */

    DecoratedServletResponse response = new DecoratedServletResponse(httpResponse,
            new DecoratedServletOutputStream(inOut));

    DecoratedServletRequest newrequest = new DecoratedServletRequest(httpRequest);

    String requestPath = page.getContentItem().getActualPath();
    newrequest.setrequestURI(requestPath);
    try {
        inOut.getWriter().flush();
        //URLUtilities urls = (URLUtilities)inContext.getPageValue(PageRequestKeys.URL_UTILITIES);
        if (requestPath.endsWith(".jsp")) {
            //A dispatcherallow us to use the base directory and draft modes
            RequestDispatcher jspDispatcher = httpRequest.getRequestDispatcher(requestPath);
            jspDispatcher.include(newrequest, response); //This only applies for jsp pages.
        } else {
            FilterChain chain = (FilterChain) httpRequest.getAttribute("servletchain");
            chain.doFilter(newrequest, response); //This will capture output to our existing output class
        }
        inOut.getWriter().flush();
    } catch (ServletException ex) {
        throw new OpenEditException(ex);
    } catch (IOException ex) {
        throw new OpenEditException(ex);
    }
}

From source file:org.eclipse.orion.server.authentication.form.servlets.LoginServlet.java

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

    if (req.getParameter("login") == null && FormAuthHelper.getAuthenticatedUser(req) != null) {
        FormAuthHelper.writeLoginResponse(FormAuthHelper.getAuthenticatedUser(req), resp);
        return;/*from  ww w .  j a  v a 2  s  . c  o m*/
    }

    try {
        if (FormAuthHelper.performAuthentication(req, resp)) {
            if (req.getParameter("redirect") != null && !req.getParameter("redirect").equals("")) { //$NON-NLS-1$
                resp.sendRedirect(req.getParameter("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(
                        "/loginform?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_UNAUTHORIZED, e.getMessage());
    }

}

From source file:Servlets.ServletPelicula.java

private void cargarPelicula(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 = "";
    String mirar = "";
    Hashtable datosPelicula = new Hashtable();
    for (int i = 0; i < items.size(); i++) {
        FileItem item = (FileItem) items.get(i);
        if (!item.isFormField()) {
            urlImg = item.getName();//from w w w. ja va  2 s .co m
            if (!urlImg.equals("")) {
                String dir = getServletContext().getRealPath("/");
                String dir2 = dir.replaceAll("web", "img");
                String dir3 = dir2.replaceAll("build", "web");
                File fileFoto = new File(dir3, item.getName());
                item.write(fileFoto);
            }
        } else {
            //if(item.getFieldName().equals("chkestado"))
            mirar += " " + item.getFieldName();
            datosPelicula.put(item.getFieldName(),
                    new String(item.getString().getBytes("iso-8859-1"), "UTF-8"));
        }
    }
    if (urlImg.equals("")) {
        urlImg = (String) datosPelicula.get("imgdefecto");
    }
    if (mirar != " ") {
        mirar += " ";
    }
    Pelicula nueva = new Pelicula(datosPelicula.get("nombre").toString(),
            datosPelicula.get("director").toString(),
            Integer.parseInt(datosPelicula.get("duracion").toString()),
            datosPelicula.get("descripcion").toString(), true, urlImg);
    String estado = (String) datosPelicula.get("chbestado");
    boolean disponible = false;
    if (estado != null) {
        disponible = true;
        nueva.setEstado(disponible);
    }
    String mod = (String) datosPelicula.get("Modifica");
    if (mod == null) {
        ctrlPelicula.altaPelicula(nueva);
    } else {
        int id = Integer.parseInt((String) datosPelicula.get("Modifica"));
        nueva.setIdPelicula(id);
        ctrlPelicula.modificapelicula(nueva);
    }
    RequestDispatcher aux = request.getRequestDispatcher("/abmPelicula.jsp");
    aux.include(request, response);
}

From source file:servlet.login.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w  w  w  .j  a  va 2  s  .  c om
 *
 * @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, SQLException, ClassNotFoundException {
    response.setContentType("text/html;charset=UTF-8");
    try (PrintWriter out = response.getWriter()) {
        /* TODO output your page here. You may use following sample code. */

        out.println("<!DOCTYPE html>");
        out.println("<html>");
        out.println("<head>");
        out.println("<title> Desarrollo</title>");
        out.println("</head>");
        out.println("<body>");
        out.println("</body>");
        out.println("</html>");

        String U, P;

        U = request.getParameter("email");
        P = DigestUtils.sha1Hex(request.getParameter("pass"));

        DAO_usuario consultar = new DAO_usuario();
        Conexion con = new Conexion();
        if (!con.conectar()) {
            response.setContentType("text/html");

            out.println("<script type=\"text/javascript\">");
            out.println("alert('[ERROR] Al conectar');");

            out.println("</script>");

            out.println("<script type=\"text/javascript\">");
            out.println("window.location=\"iniciar_sesion.jsp\";");

            out.println("</script>");

        } else {

            if (!consultar.Usuario_Correcto(U, P)) {
                response.setContentType("text/html");
                out.println("<script type=\"text/javascript\">");
                out.println("alert('[ERROR] Al iniciar sesion.');");

                out.println("</script>");

                out.println("<script type=\"text/javascript\">");
                out.println("window.location=\"iniciar_sesion.jsp\";");

                out.println("</script>");

            } else {

                /*
                 ResultSet usuario;
                         
                 usuario =  consultar.Select_Usuario(U, P);
                         
                 String sexo,nickname;
                 sexo = usuario.getString("sexo");
                 nickname = usuario.getString("usuario");
                 int tipo_usuario = usuario.getInt("tipo_usuario");
                 */

                HttpSession mysesion = request.getSession();
                ServletContext ctx = getServletContext();

                mysesion.setAttribute("U", U);
                mysesion.setAttribute("P", P);
                /*
                mysesion.setAttribute("sexo",sexo);
                mysesion.setAttribute("tipo_usuario",tipo_usuario);
                mysesion.setAttribute("nickname",nickname);
                */
                RequestDispatcher dispatcher = ctx.getRequestDispatcher("/desarrollo.jsp");

                dispatcher.include(request, response);

            }
        }
    }
}