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

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

  1. 1.导入依赖

  org.springframework.boot
  spring-boot-starter-thymeleaf
  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;
  }
}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/871178.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-13
下一篇 2022-05-13

发表评论

登录后才能评论

评论列表(0条)

保存