SpringBoot中使用Controller和页面的结合可以很好地实现用户的功能及页面数据的传递。可是在返回页面的时候居然会出现404或者500的错误,我总结了一下如何实现页面的返回以及这里面所包含的坑。html
SpringBoot中对Thymeleaf的集成已经基本完善,但在特殊状况下,并不须要或者不能使用Thymeleaf,因此分红两种状况对页面的返回进行阐述。spring
首先说一下这两种状况下都会发生的错误,也是新手们常常会出现的错误。缓存
直接上代码:mvc
@RestController public class TestController { @RequestMapping("/") public String index() { return "index"; } }
这个代码的初衷是返回index.html页面,可是执行的结果是在页面中输出index。app
缘由分析:@RestController注解至关于@ResponseBody和@Controller合在一块儿的做用。在使用@RestController注解Controller时,Controller中的方法没法返回jsp页面,或者html,配置的视图解析器 InternalResourceViewResolver不起做用,返回的内容就是Return 里的内容。jsp
包括在Mapping注解使用的同时使用@ResponseBody时也会出现一样的问题。spring-boot
解决办法:①去除@ResponseBody或将含有Rest的注解换成对应的原始注解;spa
②不经过String返回,经过ModelAndView对象返回,上述例子可将return语句换成下面的句子:3d
return new ModelAndView("index");
在使用ModelAndView对象返回的时候,不须要考虑有没有@ResponseBody相似的注解。code
还有一个须要注意的点:@RequestMapping中的路径必定不要和返回的页面名称彻底相同,这样会报500的错误!!!!
以下面这样是不行的:
@Controller public class TestController { @RequestMapping("/index") public String idx() { return "index"; } }
--------------------------------------------------------分隔线-----------------------------------------------
一、在不使用模板引擎的状况下:
在不使用模板引擎的状况下,访问页面的方法有两种:
1)将所须要访问的页面放在resources/static/文件夹下,这样就能够直接访问这个页面。如:
在未配置任何东西的状况下能够直接访问:
而一样在resources,可是在templates文件夹下的login.html却没法访问:
2)使用redirect实现页面的跳转
示例代码(在页面路径和上面一致的状况下):
@Controller public class TestController { @RequestMapping("/map1") public String index() { return "redirect:index.html"; } @RequestMapping("/map2") public String map2() { return "redirect:login.html"; } }
执行结果:
这说明这种方法也须要将html文件放在static目录下才能实现页面的跳转。
固然仍是有终极解决方案来解决这个存放路径问题的,那就是使用springmvc的配置:
spring: mvc: view: suffix: .html static-path-pattern: /** resources: static-locations: classpath:/templates/,classpath:/static/
这样配置后,map1和map2均可以访问到页面了。
二、使用Thymeleaf模板引擎:
先将所须要的依赖添加至pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> <version>2.1.6.RELEASE</version> </dependency>
一样的页面路径下将controller代码修改为下面的代码:
@Controller public class TestController { @RequestMapping("/map1") public String index() { return "index"; } /** 下面的代码能够实现和上面代码同样的功能 */ /*public ModelAndView index() { return new ModelAndView("index"); }*/ @RequestMapping("map2") public String map2() { return "login"; } }
执行结果:
这又说明一个问题,所须要的页面必须放在templates文件夹下。固然也能够修改,更改配置文件:
spring: thymeleaf: prefix: classpath:/static/ suffix: .html cache: false #关闭缓存
更改prefix对应的值能够改变Thymeleaf所访问的目录。但好像只能有一个目录。
综上:模板引擎的使用与否均可以实现页面的访问。区别在于页面所存放的位置以及访问或返回的时候后缀名加不加的问题。