springboot項目,如果想使用controller來實現跳轉頁面,
除了引入依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>
配置類:
@Configuration public class WebAppConfingurer implements WebMvcConfigurer { //還可以通過extends WebMvcConfigurationSupport @Override public void configurePathMatch(PathMatchConfigurer configurer) { configurer.setUseSuffixPatternMatch(false); } //配置資源映射路徑 @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/**") .addResourceLocations("classpath:/templates/") .addResourceLocations("classpath:/static/"); } }
項目結構:
並將靜態文件放在指定的目錄中,書寫controller
@RestController public class HelloController { @RequestMapping("/") public String hello(Model model){ return "/index"; } }
等等,有沒有發現一個容易忽視的問題
@RestController
因為這個注解包含了@Controller及@ResponseBody的功能,因為@ResponseBody會將類中的方法返回值以json字符串的形式返回.所以會造成問題,就像這樣:
我在這個注解暗地里使壞下檢查了一遍一遍的其他配置,一度懷疑自己菜的摳腳.后來在網上看到其他朋友的博客,才注意到這里
所以,想要正確的訪問靜態頁面, 就需要將@RestController注解換成@Controller
當然,如果需要這個類中的某個方法返回json數據,同樣可以將@ResponseBody放在對應的方法上
ok,將來一定要牢記基礎,不再犯這樣的低級錯誤