简体   繁体   中英

sendredirect vs requestdispatcher

I have a Java application server under the following URL:-

http://t4-dev.pta.com/gui

The user who lands to this page will be asked to login using CAS Server and the URL is returned back to http://t4-dev.pta.com/gui/ReturnLoginViaMax .

I have implemented a Servlet to handle this URL -

public class CasRedirectServlet extends HttpServlet{
    public void service(HttpServletRequest req, HttpServletResponse res)
            throws IOException, ServletException{

        //RequestDispatcher rd = req
        //      .getRequestDispatcher("/test.jsp");
        RequestDispatcher rd = req.getRequestDispatcher("banana/index.html#/dashboard/file/t4.json");
        rd.forward(req, res);
        //res.sendRedirect("banana/index.html#/dashboard/file/t4.json");
    }
}

so, now if the user hits the above servlet he will be redirected to another json file:-

banana/index.html#/dashboard/file/t4.json

This works if the If I do a sendredirect but when I use requestdispatcher it fails

message /gui/banana/index.html#/dashboard/file/t4.json

description The requested resource is not available.

I'm not sure why the above resource is not found.

It doesn't work because your path contains a URL token (the part following the # sign), which is a client-side thing interpreted by the browser only, while RequestDispatcher.forward() does a server-side internal forward and does not send the token to the browser.

If you want to use URL tokens in this way, your only option is to use sendRedirect() . This triggers a round-trip to the browser and updates the actual URL that the browser is accessing, thus giving the browser access to the URL token.

It is simply because forward and redirect are not the same at all.

When you redirect, you pass an URL back to the client browser. The browser interprets the given URL banana/index.html#/dashboard/file/t4.json and emits a request for URL /gui/banana/index.html , gets the page, and automatically scrolls it to the anchor /dashbord/file/t4.json (or just displays it if it cannot find the anchor).

But when forwarding, you ask the servlet container to pass the current request to the servlet able to serve the given URL and the servlet container cannot process the # part which is for a browser and gives you an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM