刚开始玩儿springboot,项目启动后发现无法访问一些前台页面,查了资料:
1.静态资源目录约定,在src/main/resources下创建templates目录【放html等页面文件】,static目录【放js,css,image等静态资源】
2.pom中引入相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
3.配置文件中加入视图解析
#视图层控制
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**
检查完发现都没问题,最后才注意到controller的注解问题:
@RestController
public class HelloWorld {
@RequestMapping("/hello")
public String hello(Model model) {
model.addAttribute("say","欢迎欢迎,热烈欢迎");
model.addAttribute("hello", "欢迎进入HTML页面");
return "index";
}
}
一般我们写接口的时候,注解都使用的是@RestController,这时候如果不做处理,前台页面上也只会显示return后的文本。官方解释,@RestController相当于@Controller和@ResponseBody合在一起的作用。所以书写controller时具体解决办法如下:
1.如果使用@RestController 注解,那么就必须使用视图解析器,否则只会返回return里面的内容
@RestController
public class HelloWorld {
@RequestMapping("/hello")
public ModelAndView hello(Model model) {
model.addAttribute("say","欢迎欢迎,热烈欢迎");
model.addAttribute("hello", "欢迎进入HTML页面");
ModelAndView mvAndView = new ModelAndView("index");
return mvAndView;
}
}
2.直接使用@Controller注解
@Controller public class HelloWorld { @RequestMapping("/hello") public String hello(Model model) { model.addAttribute("say","欢迎欢迎,热烈欢迎"); model.addAttribute("hello", "欢迎进入HTML页面"); return "index"; } }

本文详细介绍了在SpringBoot项目中解决无法访问前端页面的问题,包括正确配置静态资源目录、引入Thymeleaf依赖、设置视图解析及调整Controller注解方法。

4089

被折叠的 条评论
为什么被折叠?



