1、SpringMVC靜態頁面響應
1 package com.sv.controller; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.PathVariable; 5 import org.springframework.web.bind.annotation.RequestMapping; 6 /** 7 * 頁面展示 8 * @author jixh 9 * 10 */ 11 @Controller 12 public class PageController { 13 14 /** 15 * 展示首頁 16 * @return 17 */ 18 @RequestMapping(value="/") 19 public String indexShow() { 20 return "index"; 21 } 22 23 /** 24 * 展示其他頁面,每一個頁面請求都要寫一個對應的頁面返回處理,這樣太過麻煩,進行簡化 25 * 方法:正如所見,將請求的URL和處理函數返回的URL寫成一樣的,這樣一來就可以使用 26 * Restfaull的URL模板映射,直接將請求的URL作為返回的URL, 如此就可公用了 27 * 如果參數名稱和表達式名稱不一致時,加參數(@PathVariable(value="page") String page3) 28 * 29 */ 30 @RequestMapping(value="/{page}") 31 public String pageShow(@PathVariable String page) { 32 return page; 33 } 34 }
2、SpringBoot的視圖控制器實現靜態頁面響應
如上面SpringMVC響應靜態頁面的方法,在SpringBoot提供了專門的視圖控制器,只需要實現WebMvcConfigurer接口,重寫其addViewControllers方法就可以進行配置,原理只是簡單的重定向,但是在使用過程中遇到報404的問題,多次嘗試,發現有個小坑,記錄一下。
原因如下:
SpringBoot有很多的默認。就resources目錄而言,在不配置靜態資源目錄的情況下,默認static目錄中存公開的靜態資源,而templates目錄中存放模板文件。這里就有個問題,如果一個test.html文件中不涉及數據填充,只當作靜態頁面時,感覺放在兩個目錄中都可以,只是是否公開的區別而已?然而卻不是這樣,,,
在不引入Freemarker或Thymeleaf的jar包時,如果按照上面的方法,將test.html文件放在templates下時是不起作用的,表示找不到該文件(404),此時templates模板文件目錄不起作用。必須放在static下才能被controller方法返回。使用模板引擎后,放在任意目錄中都可以。
目錄結構如下:
視圖控制器配置類如下:
1 package com.huawei.myconfig; 2 3 import org.springframework.context.annotation.Configuration; 4 import org.springframework.web.servlet.config.annotation.ViewControllerRegistry; 5 import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 6 @Configuration//標志當前類在啟動的時候會被加載 7 public class MyConfiguration implements WebMvcConfigurer { 8 //視圖控制器配置 9 @Override 10 public void addViewControllers(ViewControllerRegistry registry) { 11 //urlPath:瀏覽器輸入的地址 viewName:該地址跳轉到的頁面,不加templates文件夾和.html 12 //registry.addViewController("/left").setViewName("left");錯誤的寫法 13 registry.addViewController("/login").setViewName("left.html"); 14 } 15 16 }
還有一件事:這種視圖返回方法的urlPath和viewName不能相同,否則會報500異常(
There was an unexpected error (type=Internal Server Error, status=500).
Circular view path [left]: would dispatch back to the current handler URL [/left] again. Check your ViewResolver setup! (Hint: This may be the result of an unspecified view, due to default view name generation.)
),
使用模板引擎時可以省略后綴名.html等,但返回靜態資源時則不能省略,就像請求.css,.js文件一樣。
controller類如下
1 package com.huawei.test; 2 3 import org.springframework.stereotype.Controller; 4 import org.springframework.web.bind.annotation.RequestMapping; 5 import org.springframework.web.bind.annotation.ResponseBody; 6 7 @Controller 8 public class Test { 9 @RequestMapping("/") 10 @ResponseBody 11 public String hello(){ 12 return "hello Spring boot"; 13 } 14 15 @RequestMapping("/test") 16 @ResponseBody 17 public String test(){ 18 return "舉杯邀明月,對影成三人"; 19 } 20 21 @RequestMapping("/page") 22 public String left(){ 23 return "left.html"; 24 } 25 }
如要轉載,請注明出處。