124697
124697

Reputation: 21901

How can I redirect but keep the URL the same

I am doing the following, but the url in the address bar changes. from /test to localhost:8080... Is it possible to keep the url the same in the address bar?

<servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>xxx.xxxx.Servlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>/test</url-pattern>
    </servlet-mapping>

Servlet.java

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        String path = request.getRequestURI();
        response.sendRedirect("http://localhost:8080"+path);
    }

Upvotes: 0

Views: 1380

Answers (2)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280168

You have to first understand that your Servlets (HttpServlet) and the Servlet container they're running in are implementing an HTTP stack. HTTP is a request-response protocol.

The client sends an HTTP request and the server (your Servlet container) replies with an HTTP response. In this case,

response.sendRedirect("http://localhost:8080"+path);

it is responding with a 302, indicating redirection. How your client handles this is up to them. Typically, a browser client will send a new HTTP GET request to the redirection target. This will force a page refresh/renew.

If that's not the behavior you want, you need to change your client behavior. For example, you can put part of your client logic within an iframe. You'd then have the redirect only refresh the iframe.

Upvotes: 1

Ali Sepehri.Kh
Ali Sepehri.Kh

Reputation: 2508

You can use forward instead of redirect. I wrote a method that gets a servlet's name and dispatch it:

protected void gotoServlet(HttpServletRequest req, HttpServletResponse resp,String servletName) throws ServletException, IOException {

    RequestDispatcher dispatcher = this.getServletContext().getNamedDispatcher(servletName);
    dispatcher.forward(req,resp);
}

Upvotes: 1

Related Questions