Spring boot 报错:Circular view path [...]: would dispatch back to the current handler

来源:互联网 发布:浙江师范大学知行学院 编辑:程序博客网 时间:2024/06/07 11:32

转载自 http://blog.csdn.net/wthfeng/article/details/52742830

在对mvc进行测试时,即便指定了配置文件中的视图解析依然没有作用,测试时会报异常:

javax.servlet.ServletException: Circular view path [list]: would dispatch back to the current handler URL [/list] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
网上提到此问题的有:
http://stackoverflow.com/questions/18813615/how-to-avoid-the-circular-view-path-exception-with-spring-mvc-test
以及
https://myshittycode.com/2014/01/17/mockmvc-circular-view-path-view-would-dispatch-back-to-the-current-handler-url-view-again/

摘录答案中的话,When you don’t declare a ViewResolver, spring registers a default InternalResourceViewResolver which creates instances of JstlView for rendering the View.
当你没有声明ViewResolver时,spring会给你注册一个默认的ViewResolver,其是JstlView的实例。它通过RequestDispatcher寻找资源(视图),不过这个资源也可能是Servlet,也就是说,Controller中方法返回字符串(视图名),也可能会解析成Servlet。当你的请求路径与视图名相同时,就会发生死循环。

这就是异常提示的信息。不过我依然不明白为什么配置了视图解析还是不行,依据网上的方法可以解决问题,那就是在测试类中再配置一遍视图

@ContextConfiguration(classes = {com.wthfeng.hello.config.WebConfig.class}) //加载配置文件
@WebAppConfiguration //测试时启动一个web服务
@RunWith(SpringJUnit4ClassRunner.class) //表明用spring test进行测试
public class TestJavaConfig {

private MockMvc mockMvc;@InjectMocksprivate StudentController studentController;@Mockprivate StudentService studentService;@Beforepublic void setUp(){    MockitoAnnotations.initMocks(this);    InternalResourceViewResolver resolver = new InternalResourceViewResolver(); //配置视图解析器    resolver.setPrefix("/WEB_INF/views");    resolver.setSuffix(".jsp");    mockMvc = MockMvcBuilders.standaloneSetup(studentController).setViewResolvers(resolver).build();}@Testpublic void testList()throws Exception{    mockMvc.perform(get("/list")).andExpect(view().name("list")).andExpect(model().attributeExists("StudentList"));}

}

阅读全文
0 0
原创粉丝点击