Spring-boot(二)--thymeleaf
- @Controller
- @RequestMapping("/")
- public class MessageController {
- private final MessageRepository messageRepository;
- @Autowired
- public MessageController(MessageRepository messageRepository) {
- this.messageRepository = messageRepository;
- }
- @RequestMapping
- public ModelAndView list() {
- Iterable<Message> messages = this.messageRepository.findAll();
- return new ModelAndView("messages/list", "messages", messages);
- }
- @RequestMapping("{id}")
- public ModelAndView view(@PathVariable("id") Message message) {
- return new ModelAndView("messages/view", "message", message);
- }
- @RequestMapping(params = "form", method = RequestMethod.GET)
- public String createForm(@ModelAttribute Message message) {
- return "messages/form";
- }
- @RequestMapping(method = RequestMethod.POST)
- public ModelAndView create(@Valid Message message, BindingResult result,
- RedirectAttributes redirect) {
- if (result.hasErrors()) {
- return new ModelAndView("messages/form", "formErrors", result.getAllErrors());
- }
- message = this.messageRepository.save(message);
- redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
- return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
- }
- @RequestMapping("foo")
- public String foo() {
- throw new RuntimeException("Expected exception in controller");
- }
- }
注:@Controller:1:spring的控制层。2:spring的注解之一放在类名之前3:spring配置文件中如果配置了扫描包路径,自动检测该注释的类并注入。4:spring控制层可以接收请求,并且返回响应。
@RequestMapping:用户请求路径是http://localhost:8080/项目名/类的@RequestMapping的value值/方法的@RequestMapping的value值。
@Autowired:依赖注入。
@PathVariable:rest访问方式获取参数传递
ModelAndView:一次性返回model和view2个对象,有7个构造函数,用来设定返回对象和视图,也可以用set方法设置。
@ModelAttribute:获取页面传递参数。也可以这样用
- @ModelAttribute("user")
- public User addAccount() {
- return new User("jz","123");
- }
- @RequestMapping(value = "/helloWorld")
- public String helloWorld(@ModelAttribute("user") User user) {
- user.setUserName("jizhou");
- return "helloWorld";
- }
@SessionAttributes("user")用户同上只是使用范围不同而已。
RedirectAttributes:我的理解是controller控制层跳转到控制层传递参数用的。
@Valid:对实体类的一个验证。验证符合jpa的标准。要和BindingResult result配合使用,如果验证不通过的话,result.hasErrors(),跳转 。如一个实体类标准:
- import javax.validation.constraints.Min;
- import javax.validation.constraints.NotNull;
- import org.hibernate.validator.constraints.NotBlank;
- public class User {
- private String username;
- private String password;
- private int age;
- @NotBlank(message="用户名不能为空")
- public String getUsername() {
- return username;
- }
- public void setUsername(String username) {
- this.username = username;
- }
- @NotNull(message="密码不能为null")
- public String getPassword() {
- return password;
- }
- public void setPassword(String password) {
- this.password = password;
- }
- @Min(value=10, message="年龄的最小值为10")
- public int getAge() {
- return age;
- }
- public void setAge(int age) {
- this.age = age;
- }
- }
最后个方法就是抛出页面异常.
html主要用ThyMeleaf标签,Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fernández创建,该作者还是Java加密库Jasypt的作者。
form.html代码如下:
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org"
- xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
- layout:decorator="layout">
- <head>
- <title>Messages : Create</title>
- </head>
- <body>
- <h1 layout:fragment="header">Messages : Create</h1>
- <div layout:fragment="content"
- class="container">
- <form id="messageForm"
- th:action="@{/(form)}"
- th:object="${message}"
- action="#"
- method="post">
- <div th:if="${#fields.hasErrors('*')}"
- class="alert alert-error">
- <p th:each="error : ${#fields.errors('*')}"
- th:text="${error}">
- Validation error
- </p>
- </div>
- <div class="pull-right">
- <a th:href="@{/}" href="messages.html">
- Messages
- </a>
- </div>
- <label for="summary">Summary</label>
- <input type="text"
- th:field="*{summary}"
- th:class="${#fields.hasErrors('summary')} ? 'field-error'"/>
- <label for="text">Message</label>
- <textarea
- th:field="*{text}"
- th:class="${#fields.hasErrors('text')} ? 'field-error'"></textarea>
- <div class="form-actions">
- <input type="submit" value="Create"/>
- </div>
- </form>
- </div>
- </body>
- </html>
list.html代码如下:
- <!DOCTYPE html>
- <html xmlns:th="http://www.thymeleaf.org"
- xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
- layout:decorator="layout">
- <head>
- <title>Messages : View all</title>
- </head>
- <body>
- <h1 layout:fragment="header">Messages : View all</h1>
- <div layout:fragment="content" class="container">
- <div class="pull-right">
- <a href="form.html" th:href="@{/(form)}">Create Message</a>
- </div>
- <table class="table table-bordered table-striped">
- <thead>
- <tr>
- <td>ID</td>
- <td>Created</td>
- <td>Summary</td>
- </tr>
- </thead>
- <tbody>
- <tr th:if="${messages.empty}">
- <td colspan="3">
- No messages
- </td>
- </tr>
- <tr th:each="message : ${messages}">
- <td th:text="${message.id}">1</td>
- <td th:text="${#calendars.format(message.created)}">
- July 11, 2012 2:17:16 PM CDT
- </td>
- <td>
- <a href="view.html"
- th:href="@{'/' + ${message.id}}"
- th:text="${message.summary}">
- The summary
- </a>
- </td>
- </tr>
- </tbody>
- </table>
- </div>
- </body>
- </html>
view.html代码如下:
- <html xmlns:th="http://www.thymeleaf.org"
- xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
- layout:decorator="layout">
- <head>
- <title>Messages : View</title>
- </head>
- <body>
- <h1 layout:fragment="header">Messages : Create</h1>
- <div layout:fragment="content"
- class="container">
- <div class="alert alert-success"
- th:if="${globalMessage}"
- th:text="${globalMessage}">
- Some Success message
- </div>
- <div class="pull-right">
- <a th:href="@{/}" href="list.html">
- Messages
- </a>
- </div>
- <dl>
- <dt>ID</dt>
- <dd id="id" th:text="${message.id}">123</dd>
- <dt>Date</dt>
- <dd id="created"
- th:text="${#calendars.format(message.created)}">
- July 11, 2012 2:17:16 PM CDT
- </dd>
- <dt>Summary</dt>
- <dd id="summary"
- th:text="${message.summary}">
- A short summary...
- </dd>
- <dt>Message</dt>
- <dd id="text"
- th:text="${message.text}">
- A detailed message that is longer than the summary.
- </dd>
- </dl>
- </div>
- </body>
- </html>
注th标签的引用就是首先要注入标签头,xmlns:th="http://www.thymeleaf.org"放入html标签内就可以了,
# 代表 获取对象 从 messages bundle 也就是消息的资源本地化文件
$ 表示从model里面获取
- <div class="col-sm-9">
- <input type="text" th:field="*{id}" placeholder="Order Id" class="col-xs-10 col-sm-5" />
- <p style="color:red" th:if="${#fields.hasErrors('*{id}')}" th:errors="*{id}"></p>
- </div>
th:fragment=“public” 相当于 include标签
th:each="user : ${users}" 相当于c:foreach 使用时候
如上面
<tr th:each="user : ${users}">
<td th:text="${user.id}">01</td>
<td th:text="${user.name}">朱遇平</td>
<td th:text="${user.xx}">java</td>
<td th:text="${user.xx}">程序员</td>
</tr>
th:href="@{/}"动态设置url参数
<form action="#" th:action="@{/users/add}" th:object="${myuser}" method="post">
这里th:Object表示表单与 改myuser注入的实体映射,
在表单 th:field="*{id} 则表示 该表单的值 与 myuser的id绑定
th:if="${#fields.hasErrors('*')}"
th:if="${#strings.isEmpty(status)}"
${not #strings.isEmpty(status)}
if判断显示。
- <div class="col-sm-9">
- <input type="text" th:field="*{id}" placeholder="Order Id" class="col-xs-10 col-sm-5" />
- <p style="color:red" th:if="${#fields.hasErrors('*{id}')}" th:errors="*{id}"></p>
- </div>
th:errors错误信息显示如上图。
Spring-boot(二)--thymeleaf的更多相关文章
- Spring Boot整合 Thymeleaf 模板引擎
什么是Thymeleaf Thymeleaf是一款用于渲染XML.XHTML.HTML5内容的模板引擎.类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框 ...
- spring boot 与 thymeleaf (2): 常用表达式
在asp.net mvc 中, 有一个视图解析器, 可以支持Razor语法. 使用起来, 是非常的方便, 并且, 写在前台页面的后台方法, 是可调试的. 但是在java中, 目前我还没有接触到, 像. ...
- 一个小demo熟悉Spring Boot 和 thymeleaf 的基本使用
目录 介绍 零.项目素材 一. 创建 Spring Boot 项目 二.定制首页 1.修改 pom.xml 2.引入相应的本地 css.js 文件 3.编辑 login.html 4.处理对 logi ...
- Spring Boot 2 + Thymeleaf:表单字段绑定、表单提交处理
Spring Boot中Thymeleaf对表单处理的一些用法:(1)使用th:field属性:进行表单字段绑定(2)使用ids对象:一般用于lable配合radio或checkbox使用(3)表单提 ...
- Spring Boot整合Thymeleaf模板引擎
什么是Thymeleaf Thymeleaf是一款用于渲染XML.XHTML.HTML5内容的模板引擎.类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框 ...
- 从零开始的Spring Boot(5、Spring Boot整合Thymeleaf)
Spring Boot整合Thymeleaf 写在前面 从零开始的Spring Boot(4.Spring Boot整合JSP和Freemarker) https://www.cnblogs.com/ ...
- Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控
Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...
- Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例
Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...
- Spring Boot2 系列教程(九)Spring Boot 整合 Thymeleaf
虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板, ...
- Spring Boot 二十个注解
Spring Boot 二十个注解 占据无力拥有的东西是一种悲哀. Cold on the outside passionate on the insede. 背景:Spring Boot 注解的强大 ...
随机推荐
- Unity3d如何profile模拟器
最近有反馈X2在一些模拟器中运行偶尔非常卡,达到5秒左右,而这类问题在真机上没出现过,于是想用unity profile下模拟器.但模拟器是运行在虚拟机里面的,市面上大多模拟器并没有提供虚拟机网络设置 ...
- 对Android中的堆栈的理解(Stack)
版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/Ln_ZooFa/article/details/50337529 堆栈空间分配 栈(操作系统): ...
- 在python里调用java的py4j的使用方法
py4j可以使python和java互调 py4j并不会开启jvm,需要先启动jvm server,然后再使用python的client去连接jvm GatewayServer实例:允许python程 ...
- Error-MVC: 未能找到路径“D:\\DsWeb\DS.Web\dist\bin\roslyn\csc.exe”的一部分。
ylbtech-Error-MVC: 未能找到路径“D:\\DsWeb\DS.Web\dist\bin\roslyn\csc.exe”的一部分. 1.返回顶部 1, “/”应用程序中的服务器错误. 未 ...
- pip安装pycrypto报错:Microsoft Visual C++ 14.0 is required. 和 SSLError: HTTPSConnectionPool的解决办法
今天本打算把[Python3爬虫]网易云音乐爬虫 的代码敲一遍, 但是在安装pycrypto老是报错, 由于我计算是win10, 并且也有vs2017 python3环境下安装pycrypto的一些问 ...
- Spring 拦截器postHandle无法修改Response的原因
如果controller跳转至页面,postHandle是没问题的. 如果@ResponseBody注释 或者返回 ResponseEntity,在postHandle拦截器中修改请求头,是无效的. ...
- Pilosa文档翻译(二)入门指南
目录 开始 Pilosa 简单项目 创建架构(Create the Schema) 从CVS文件导入数据 做一些查询(Queries) 接下来做什么? Pilosa支持默认使用JSON的HTTP接口. ...
- Spring Boot系列——AOP配自定义注解的最佳实践
AOP(Aspect Oriented Programming),即面向切面编程,是Spring框架的大杀器之一. 首先,我声明下,我不是来系统介绍什么是AOP,更不是照本宣科讲解什么是连接点.切面. ...
- Troubleshooting Scheduler Autotask Issues (Doc ID 1561498.1)
In this Document Purpose Troubleshooting Steps References APPLIES TO: Oracle Database - Enterp ...
- 【Java】类加载过程
JVM把class文件加载到内存,并对数据进行校验.解析和初始化,最终形成JVM可以直接使用的Java类型的过程. 类加载的过程主要分为三个部分: 加载 链接 初始化 而链接又可以细分为三个小部分: ...