springboot返回视图
上篇文章我新建了第一个springboot程序,并通过访问http://localhost:8080/getUsers返回一个字符串成功了,因为我在getUsers()方法上加了@ResponseBody注解,这里返回的字符串的MIME类型其实是application/json,如果我现在写一个如下方法,这个方法上并没有加@ResponseBody注解,如下:
@RequestMapping("/toAdd") public String toAdd(){ return "toAdd"; }
通过访问http://localhost:8080/toAdd却得到了如下的页面,出错了javax.servlet.ServletException: Circular view path [toAdd]: would dispatch back to the current handler URL [/toAdd] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.):
解决方法:
1、这是因为springboot找寻视图的时候默认是去找以ftl结尾的freemarker视图,freemarker跟jsp的作用是一样的,都可以作为view层的载体,要想解决上面的错误,需要在pom.xml中加入freemarker相关的starter,实际上就是引入了freemarker相关的jar包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-freemarker</artifactId> </dependency>
2.之后呢,因为我这里返回的是"toAdd",springboot回去找“toAdd.ftl”,去哪里找?去类路径下的templates文件夹,所以呢,我需要这样排列项目的结构,其中templates文件夹用于放置ftl文件,static是默认的js,css存放的路径:
toAdd.ftl的内容是:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title here</title> </head> <body> toAdd.ftl </body> </html>
做了上边两步操作之后,我们重新启动应用程序,再刷新:
一切就正常了。