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,将来一定要牢记基础,不再犯这样的低级错误