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所訪問的目錄。但好像只能有一個目錄。
綜上:模板引擎的使用與否均可以實現頁面的訪問。區別在於頁面所存放的位置以及訪問或返回的時候後綴名加不加的問題。