Spring boot中如何使用Model进行传值以及Thymeleaf的用法_springboot model传值

52 阅读2分钟
public String index(Model model){ 
return "index";
}

}


@Controller:这个标签是结点标签的标识,结点主要用于传值和跳转页面,所以看到这个标签大家就应该联想到这些。  
 @Resource  
 private StudentServiceImp ssi; 这句话的意思是小编将StudentServiceImp 实体化了,到时候就直接可以调用StudentServiceImp 的方法了。


@RequestMapping(value = “/”)这个注解的意思就是当访问localhost8080是默认的就会跳转到index页面,这也是通过映射来找到页面


创建Index页面



index

"<html lang=“en” xmlns:th=“<http://www.thymeleaf.org>”:这段代码就是引入了th模板


当然做到这里我们的前期准备就完成了。


### 主体内容


1. **如果你要传入的是一个字符串**



@Controller public class NodeController { @Resource private StudentServiceImp ssi;

@RequestMapping(value = "/")
public String index(Model model){ 
String students ="刘洋";
 model.addAttribute("s",students)
return "index";
}

}


model.addAttribute(“s”,students) s就为传入前端的标识  
 Html代码如下



index

2. **如果你要传入的是一个list集合.**  
 我们都知道如果传入的是一个list集合,前端就必须要展示list集合的属性。



@Controller public class NodeController { @Resource private StudentServiceImp ssi;

@RequestMapping(value = "/")
public String index(Model model){ 
List<Student> list = ssi.findStudentByAge(15);
 model.addAttribute("s",list)
return "index";
}

}


Html代码如下,这里只是拿出了s中的属性。



index
<tr >
    <td>学生Id</td>
    <td th:text="${i.id}"></td>
</tr>

<tr >
      <td>学生姓名</td>
     <td th:text="${i.name}"></td>

</tr>
<tr >
    <td>学生分数</td>
    <td th:text="${i.score}"></td>

</tr>
<tr >
    <td>教师建议</td>
    <td th:text="${i.suggestion}"></td>
</tr>

3. **如果你要传入的是一个对象.**



@Controller public class NodeController { @Resource private StudentServiceImp ssi;

@RequestMapping(value = "/") public String index(Model model){ Student students = ssi.findStudentById(201713140001); model.addAttribute("s",students); return "index"; } }


Html代码如下,这里就要用到get方法了。



index

收集整理了一份《2024年最新物联网嵌入式全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升的朋友。 img img

如果你需要这些资料,可以戳这里获取

一个人可以走的很快,但一群人才能走的更远!不论你是正从事IT行业的老鸟或是对IT行业感兴趣的新人

都欢迎加入我们的的圈子(技术交流、学习资源、职场吐槽、大厂内推、面试辅导),让我们一起学习成长!