Ben Ben - 1 year ago 186
Java Question

Circular View Path Error, Spring MVC

I'm trying to do the tutorial ->

When I run it, it says Circular View Path[greeting], why?

In the tutorial, one thing i dont understand is what the following does and why it works:

return "greeting";

Code snippet:

package hello;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

public class GreetingController {
public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
model.addAttribute("name", name);
return "greeting";

Answer Source

You might have skipped a step while following the tutorial.

I'll explain why you get the behavior you are seeing and you can decide what to do afterwards.

You probably started your application the, args);

in the tutorial Application class' main method. By default, because of @EnableAutoConfiguration (and other components on the classpath), a DispatcherServlet will be registered for you which provides a default UrlBasedViewResolver that doesn't set a prefix or suffix to the views it resolves.

In your @Controller handler method, when you do

return "greeting";

Spring will use the UrlBasedViewResolver to resolve a view name. In this case, the view name will simply be greeting. In normal cases, once that is done, it will use the Servlet API's HttpServletRequest#getRequestDispatcher(String) passing in that view name. That method returns a RequestDispatcher which points to the handler for that path.

In our case, before getting the RequestDispatcher, Spring will compare the view name (which resolves to a path) and the current request's path. It will find that they are both equal. In other words, a request to /greeting will be handled by returning a view to /greeting which will be handled by the same @Controller handler method, and this forever. Spring detects this and tells you that you have a circular view path, ie. you would loop infinitely.

Find out how @EnableAutoConfiguration works and change your configuration so that you can define your own UrlBasedViewResolver or InternalResourceViewResolver which sets prefix and suffix appropriately.

You can read more about view name resolution in the official Spring MVC documentation.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download