天天看点

springboot中ModelAndView跳转设置

想要在springboot项目中跳转页面可以使用ModelAndView

前提是首先需要导入thymeleaf的依赖

<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
            <!-- 版本号是根据你的springboot项目的版本来 可以写也可以不写
            (不写默认就是根据创建的springboot项目本版本设置)-->
            <version>2.6.5</version>
 	</dependency>
           

如果不想用自带的版本 可以去 https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf

mvnrepository上面找到你想要的版本进行设置

thymeleaf默认的是找.html文件,在templates文件夹下面的 如果你想更改搜索的位置 你可以在application.yml或者application.properties 中设置

下面是application.yml的设置

thymeleaf:
	#这两个值都是默认的前后缀 可以根据需要自行更改
    suffix: .html
    prefix: classpath:/templates
           

跳转的路径写法

我要跳转的目标是:templates/admin/login.html

springboot中ModelAndView跳转设置

controller层写法就是:

@RequestMapping("/toLogin")
public ModelAndView loginPage(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("admin/login");
        return modelAndView;
    }
           

这样就可以跳转过去

注意:如果找不到页面需要查看maven中是否加载了thymeleaf的依赖

springboot中ModelAndView跳转设置

再就是编译后的target中是否有跳转的页面

springboot中ModelAndView跳转设置

最后使用thymeleaf时前端加上下面的这个数据才能生效

xmlns:th="http://www.thymeleaf.org
           
<!DOCTYPE html>
<!--使用前端时记得加上这个 在html标签后加上 -->
<html xmlns:th="http://www.thymeleaf.org">

  <head>
    <title>Good Thymes Virtual Grocery</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link rel="stylesheet" type="text/css" media="all" 
          href="../../css/gtvg.css" th:href="@{/css/gtvg.css}" />
  </head>

  <body>
  
    <p th:text="#{home.welcome}">Welcome to our grocery store!</p>
  
  </body>

</html>