美文网首页
SpringBoot 项目启动后无法打开html,jsp等页面问

SpringBoot 项目启动后无法打开html,jsp等页面问

作者: 清_晨_ | 来源:发表于2018-12-08 08:48 被阅读189次

今天试着在原来rest接口项目的基础上,添加一个前端页面来做一个前后端的整合,配置完,启动后发现前台只显示页面名称。看了半天,发现配置文件没有问题。最后翻了翻官方文档,终于找到了解决办法。

1.pom中引入依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
 </dependency>

2.配置文件中加入视图解析

#视图层控制
spring.mvc.view.prefix=classpath:/templates/
spring.mvc.view.suffix=.html
spring.mvc.static-path-pattern=/static/**

3.controller层的正确书写

这一步一定要注意,一般我们写接口的时候,注解都使用的是@RestController,这时候如果不做处理,前台页面上也只会显示return后的内容,也就是一个页面的名称。官方文档的解释:@RestController is a stereotype annotation that combines @ResponseBody and @Controller.
大概意思是:@RestController相当于@Controller和@ResponseBody合在一起的作用。所以书写controller时具体解决办法如下:

1.如果使用@RestController 注解,那么就必须使用视图解析器,否则只会返回return里面的内容

@RestController
@RequestMapping({"/api"})
public class TestController {
    @RequestMapping("/index1")
    public ModelAndView index1() {
        ModelAndView mv = new ModelAndView("hello");
        return mv;
    }
}
2.直接使用@Controller注解

@Controller
@RequestMapping({"/api"})
public class TestController {
    @RequestMapping("/index")
    public String index(){
        return "hello" ;
    }

相关文章

网友评论

      本文标题:SpringBoot 项目启动后无法打开html,jsp等页面问

      本文链接:https://www.haomeiwen.com/subject/wlifhqtx.html