SpringBoot项目打开templates下的页面(使用字符串和modelView方法)

  1. 1.导入依赖
<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
  1. 2.配置文件

在application.yml或者application.properties下

spring:
  thymeleaf:
    prefix:
      classpath: /templates   # 访问template下的html文件需要配置模板,映射
    cache: false # 开发时关闭缓存,不然没法看到实时页面

  1. 3.templates下的html文件

  1. 4.接下来有两种方式访问,使用字符串形式访问,使用modelView形式访问
package com.example.demo.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
//必须使用Controller注解不能使用restController
//因为它返回的是json数据格式,而我们要的是html页面
@Controller
public class ReflectAction {
  //  private static final Logger log = (Logger) LoggerFactory.getLogger(ReflectAction.class);
  @RequestMapping("/temTest")
  public String temTest2() {
    return "temTest";
  }

需要注意

RequestMapping里的字符串要和要访问的页面名字一样。返回值字符串也要和页面名字一样,也就是我上面写的temTest

这时候已经能够使用浏览器进行访问了


访问地址:http://10.132.181.146:10090/temTest/

如果不想要上面的方式还有另一种方式,使用modelView

new ModelAndView("temTest");双引号里面是templates下的html名字

同样可以达成目的


package com.example.demo.action;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;


@Controller
public class ReflectAction {
@RequestMapping("/temTest")    //    你想浏览器地址栏输入什么就是什么
  public ModelAndView newView() {
    ModelAndView modelAndView = new ModelAndView("temTest");    //你的html名字如果有文件
    //    文件名/html文件名

    return modelAndView;
  }
}


版权声明:本文为weixin_45058582原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。