简体   繁体   中英

sendRedirect() doens't work

I looked for a solution on this forum, but i didn't find anything that suits my problem.

I have a very simplce code

a jsp page

<html>
<body>
<jsp:include page="/servletName"/>
</body>
</html>

and a servlet

@WebServlet("/servletName")
public class reindirizzaController extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public reindirizzaController() {
        super();        
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      String redirectURL = "http://www.google.it";
      response.sendRedirect(redirectURL);       
    }

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

}

No redirect is done. I'm stuck in the jsp page and i get no error. I also tried to add return; after the response.

Since you are calling the servlet through Include , it does not make you redirect. It simply ignores.

From docs of include()

includes the content of a resource (servlet, JSP page, HTML file) in the response. In essence, this method enables programmatic server-side includes.

The ServletResponse object has its path elements and parameters remain unchanged from the caller's. The included servlet cannot change the response status code or set headers; any attempt to make a change is ignored.

First, it is bad practice to call a servlet from a jsp. As you are using @WebServlet("/servletName") , you can directly call it at http://host/context/servletName

If you really need to call it from a jsp, you must forward to the servlet instead of including it as Suresh Atta explained. So you should use :

<jsp:forward page="/servletName"/>

When you do a JSP include directive, you're essentially plopping the code you're including right on the page. In your example, you would be doing the sendRedirect in your JSP. Even if you got the redirect to work miraculously, you would get an error saying that your response has already been committed. This is because by the time your browser loads the JSP, it is already reading from the server's response. The server cannot send another response while it is already sending a response to your browser.

One way to approach this is instead of doing an include directive, create a form with your servlet path as the action. Something like:

<form name="someForm" action="/servletPath/servletName">
    <!-- some stuff here if you want -->
</form>

And then in your body tag, have it submit the form on load:

<body onLoad="document.someForm.submit();">

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