简体   繁体   中英

Controller repeatedly calling itself in Spring-MVC

I was trying to just output my request with just a direct write to the response object. This works great with servlets but with Spring-MVC I ended up creating an infinite loop for some reason I don't understand. Basically the controller just gets called repeatedly. I don't even know how that is possible.

public ModelAndView handleRequest(
        HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException
{
    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().close();
    return new ModelAndView();

}

So the question is, does anyone know why it would cause an infinite amount of re-requests to this page? It seems to only occur when I am creating a ModelAndView() with nothing in it. But in this case I don't want anything in it, just a blank page. So secondly then is there a way to accomplish that?

Try to return null , instead of ModelAndView , and call flush() instead of close() . Like this,

public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response )
        throws ServletException, IOException {

    System.out.println("I will get called infinitely");
    response.getWriter().print( "Hello World!");
    response.getWriter().flush();
    return null;    
}

NOTE: I am not sure, whether close() will commit the response or not, but flush() will.

Probably an empty viewName of the ModelAndView class will cause that the view from the current request will be used.

You can use void or @ResponseBody String as return type.

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