1. @Controller
  2. @RequestMapping("/")
  3. public class MessageController {
  4. private final MessageRepository messageRepository;
  5. @Autowired
  6. public MessageController(MessageRepository messageRepository) {
  7. this.messageRepository = messageRepository;
  8. }
  9. @RequestMapping
  10. public ModelAndView list() {
  11. Iterable<Message> messages = this.messageRepository.findAll();
  12. return new ModelAndView("messages/list", "messages", messages);
  13. }
  14. @RequestMapping("{id}")
  15. public ModelAndView view(@PathVariable("id") Message message) {
  16. return new ModelAndView("messages/view", "message", message);
  17. }
  18. @RequestMapping(params = "form", method = RequestMethod.GET)
  19. public String createForm(@ModelAttribute Message message) {
  20. return "messages/form";
  21. }
  22. @RequestMapping(method = RequestMethod.POST)
  23. public ModelAndView create(@Valid Message message, BindingResult result,
  24. RedirectAttributes redirect) {
  25. if (result.hasErrors()) {
  26. return new ModelAndView("messages/form", "formErrors", result.getAllErrors());
  27. }
  28. message = this.messageRepository.save(message);
  29. redirect.addFlashAttribute("globalMessage", "Successfully created a new message");
  30. return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
  31. }
  32. @RequestMapping("foo")
  33. public String foo() {
  34. throw new RuntimeException("Expected exception in controller");
  35. }
  36. }

注:@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:获取页面传递参数。也可以这样用

  1. @ModelAttribute("user")
  2. public User addAccount() {
  3. return new User("jz","123");
  4. }
  5. @RequestMapping(value = "/helloWorld")
  6. public String helloWorld(@ModelAttribute("user") User user) {
  7. user.setUserName("jizhou");
  8. return "helloWorld";
  9. }

@SessionAttributes("user")用户同上只是使用范围不同而已。

RedirectAttributes:我的理解是controller控制层跳转到控制层传递参数用的。

@Valid:对实体类的一个验证。验证符合jpa的标准。要和BindingResult result配合使用,如果验证不通过的话,result.hasErrors(),跳转 。如一个实体类标准:

  1. import javax.validation.constraints.Min;
  2. import javax.validation.constraints.NotNull;
  3. import org.hibernate.validator.constraints.NotBlank;
  4. public class User {
  5. private String username;
  6. private String password;
  7. private int age;
  8. @NotBlank(message="用户名不能为空")
  9. public String getUsername() {
  10. return username;
  11. }
  12. public void setUsername(String username) {
  13. this.username = username;
  14. }
  15. @NotNull(message="密码不能为null")
  16. public String getPassword() {
  17. return password;
  18. }
  19. public void setPassword(String password) {
  20. this.password = password;
  21. }
  22. @Min(value=10, message="年龄的最小值为10")
  23. public int getAge() {
  24. return age;
  25. }
  26. public void setAge(int age) {
  27. this.age = age;
  28. }
  29. }

最后个方法就是抛出页面异常.

html主要用ThyMeleaf标签,Thymeleaf是一个XML/XHTML/HTML5模板引擎,可用于Web与非Web环境中的应用开发。它是一个开源的Java库,基于Apache License 2.0许可,由Daniel Fern&aacute;ndez创建,该作者还是Java加密库Jasypt的作者。

form.html代码如下:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org"
  3. xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
  4. layout:decorator="layout">
  5. <head>
  6. <title>Messages : Create</title>
  7. </head>
  8. <body>
  9. <h1 layout:fragment="header">Messages : Create</h1>
  10. <div layout:fragment="content"
  11. class="container">
  12. <form id="messageForm"
  13. th:action="@{/(form)}"
  14. th:object="${message}"
  15. action="#"
  16. method="post">
  17. <div th:if="${#fields.hasErrors('*')}"
  18. class="alert alert-error">
  19. <p th:each="error : ${#fields.errors('*')}"
  20. th:text="${error}">
  21. Validation error
  22. </p>
  23. </div>
  24. <div class="pull-right">
  25. <a th:href="@{/}" href="messages.html">
  26. Messages
  27. </a>
  28. </div>
  29. <label for="summary">Summary</label>
  30. <input type="text"
  31. th:field="*{summary}"
  32. th:class="${#fields.hasErrors('summary')} ? 'field-error'"/>
  33. <label for="text">Message</label>
  34. <textarea
  35. th:field="*{text}"
  36. th:class="${#fields.hasErrors('text')} ? 'field-error'"></textarea>
  37. <div class="form-actions">
  38. <input type="submit" value="Create"/>
  39. </div>
  40. </form>
  41. </div>
  42. </body>
  43. </html>

list.html代码如下:

  1. <!DOCTYPE html>
  2. <html xmlns:th="http://www.thymeleaf.org"
  3. xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
  4. layout:decorator="layout">
  5. <head>
  6. <title>Messages : View all</title>
  7. </head>
  8. <body>
  9. <h1 layout:fragment="header">Messages : View all</h1>
  10. <div layout:fragment="content" class="container">
  11. <div class="pull-right">
  12. <a href="form.html" th:href="@{/(form)}">Create Message</a>
  13. </div>
  14. <table class="table table-bordered table-striped">
  15. <thead>
  16. <tr>
  17. <td>ID</td>
  18. <td>Created</td>
  19. <td>Summary</td>
  20. </tr>
  21. </thead>
  22. <tbody>
  23. <tr th:if="${messages.empty}">
  24. <td colspan="3">
  25. No messages
  26. </td>
  27. </tr>
  28. <tr th:each="message : ${messages}">
  29. <td th:text="${message.id}">1</td>
  30. <td th:text="${#calendars.format(message.created)}">
  31. July 11, 2012 2:17:16 PM CDT
  32. </td>
  33. <td>
  34. <a href="view.html"
  35. th:href="@{'/' + ${message.id}}"
  36. th:text="${message.summary}">
  37. The summary
  38. </a>
  39. </td>
  40. </tr>
  41. </tbody>
  42. </table>
  43. </div>
  44. </body>
  45. </html>

view.html代码如下:

  1. <html xmlns:th="http://www.thymeleaf.org"
  2. xmlns:layout="http://www.ultraq.net.nz/web/thymeleaf/layout"
  3. layout:decorator="layout">
  4. <head>
  5. <title>Messages : View</title>
  6. </head>
  7. <body>
  8. <h1 layout:fragment="header">Messages : Create</h1>
  9. <div layout:fragment="content"
  10. class="container">
  11. <div class="alert alert-success"
  12. th:if="${globalMessage}"
  13. th:text="${globalMessage}">
  14. Some Success message
  15. </div>
  16. <div class="pull-right">
  17. <a th:href="@{/}" href="list.html">
  18. Messages
  19. </a>
  20. </div>
  21. <dl>
  22. <dt>ID</dt>
  23. <dd id="id" th:text="${message.id}">123</dd>
  24. <dt>Date</dt>
  25. <dd id="created"
  26. th:text="${#calendars.format(message.created)}">
  27. July 11, 2012 2:17:16 PM CDT
  28. </dd>
  29. <dt>Summary</dt>
  30. <dd id="summary"
  31. th:text="${message.summary}">
  32. A short summary...
  33. </dd>
  34. <dt>Message</dt>
  35. <dd id="text"
  36. th:text="${message.text}">
  37. A detailed message that is longer than the summary.
  38. </dd>
  39. </dl>
  40. </div>
  41. </body>
  42. </html>

注th标签的引用就是首先要注入标签头,xmlns:th="http://www.thymeleaf.org"放入html标签内就可以了,

# 代表 获取对象 从 messages bundle 也就是消息的资源本地化文件

$ 表示从model里面获取

  1. <div class="col-sm-9">
  2. <input type="text" th:field="*{id}" placeholder="Order Id" class="col-xs-10 col-sm-5" />
  3. <p style="color:red" th:if="${#fields.hasErrors('*{id}')}" th:errors="*{id}"></p>
  4. </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判断显示。

  1. <div class="col-sm-9">
  2. <input type="text" th:field="*{id}" placeholder="Order Id" class="col-xs-10 col-sm-5" />
  3. <p style="color:red" th:if="${#fields.hasErrors('*{id}')}" th:errors="*{id}"></p>
  4. </div>

th:errors错误信息显示如上图。

Spring-boot(二)--thymeleaf的更多相关文章

  1. Spring Boot整合 Thymeleaf 模板引擎

    什么是Thymeleaf Thymeleaf是一款用于渲染XML.XHTML.HTML5内容的模板引擎.类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框 ...

  2. spring boot 与 thymeleaf (2): 常用表达式

    在asp.net mvc 中, 有一个视图解析器, 可以支持Razor语法. 使用起来, 是非常的方便, 并且, 写在前台页面的后台方法, 是可调试的. 但是在java中, 目前我还没有接触到, 像. ...

  3. 一个小demo熟悉Spring Boot 和 thymeleaf 的基本使用

    目录 介绍 零.项目素材 一. 创建 Spring Boot 项目 二.定制首页 1.修改 pom.xml 2.引入相应的本地 css.js 文件 3.编辑 login.html 4.处理对 logi ...

  4. Spring Boot 2 + Thymeleaf:表单字段绑定、表单提交处理

    Spring Boot中Thymeleaf对表单处理的一些用法:(1)使用th:field属性:进行表单字段绑定(2)使用ids对象:一般用于lable配合radio或checkbox使用(3)表单提 ...

  5. Spring Boot整合Thymeleaf模板引擎

    什么是Thymeleaf Thymeleaf是一款用于渲染XML.XHTML.HTML5内容的模板引擎.类似Velocity,FreeMaker模板引擎,它也可以轻易的与Spring MVC等Web框 ...

  6. 从零开始的Spring Boot(5、Spring Boot整合Thymeleaf)

    Spring Boot整合Thymeleaf 写在前面 从零开始的Spring Boot(4.Spring Boot整合JSP和Freemarker) https://www.cnblogs.com/ ...

  7. Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控

    Spring Boot(二十):使用spring-boot-admin对spring-boot服务进行监控 Spring Boot Actuator提供了对单个Spring Boot的监控,信息包含: ...

  8. Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例

    Spring Boot(十五):spring boot+jpa+thymeleaf增删改查示例 一.快速上手 1,配置文件 (1)pom包配置 pom包里面添加jpa和thymeleaf的相关包引用 ...

  9. Spring Boot2 系列教程(九)Spring Boot 整合 Thymeleaf

    虽然现在慢慢在流行前后端分离开发,但是据松哥所了解到的,还是有一些公司在做前后端不分的开发,而在前后端不分的开发中,我们就会需要后端页面模板(实际上,即使前后端分离,也会在一些场景下需要使用页面模板, ...

  10. Spring Boot 二十个注解

    Spring Boot 二十个注解 占据无力拥有的东西是一种悲哀. Cold on the outside passionate on the insede. 背景:Spring Boot 注解的强大 ...

随机推荐

  1. 03、操作RDD(transformation和action案例实战)

    1.transformation和action介绍 Spark支持两种RDD操作:transformation和action.transformation操作会针对已有的RDD创建一个新的RDD:而a ...

  2. python3 图片文字识别

    最近用到了图片文字识别这个功能,从网上搜查了一下,决定利用百度的文字识别接口.通过测试发现文字识别率还可以.下面就测试过程简要说明一下 1.注册用户 链接:https://login.bce.baid ...

  3. 【Zuul】Zuul过滤器参考资料

    #https://blog.csdn.net/chenqipc/article/details/53322830#https://github.com/spring-cloud/spring-clou ...

  4. jvm理论-class文件

    当JVM运行Java程序的时候,它会加载对应的class文件,并提取class文件中的信息存放在JVM的方法区内存中. Class文件组成 1.Class文件是一组以8位字节为基础单位的二进制流,各个 ...

  5. 未能加载文件或程序集“SuperMap.Data.dll”

    重新配置的新的开发环境,使用的是原来的工程文件,编译通过,运行报错:"未能加载文件或程序集"SuperMap.Data.dll"或它的某一个依赖项.找不到指定的模块&qu ...

  6. VirtualBox虚拟机磁盘瘦身

    操作系统 : windows7_x64 VirtualBox 版本 : 4.3.28 原理: 使用0填充虚拟系统磁盘,然后删除填充文件,再使用VBoxManage进行压缩. Linux系统磁盘瘦身 一 ...

  7. unbuntu系统( PC机 )中安装360wifi步骤

    少说废话,每一步都经过验证: 1.  首先查看一下当前使用的linux版本: gxjun@gxjun:~$ uname -r 4.8.0-59-generic 2. 将360wifi插入PC的USB中 ...

  8. 一个会学习(观察->活学->求变)的人,在任何领域都能变得强大无比

      开始今天的话题之前,我说个小故事.   很早以前有一部美剧,叫<Hero>.   大概讲的是正反两派都是一群有超能力的人,彼此为了某个巨大的阴谋互相撕逼了十多集.虽然剧情很老套,但是让 ...

  9. GPL、BSD、MIT、Mozilla、Apache、LGPL开源协议介绍

    BSD开源协议 BSD开源协议是一个给于使用者很大自由的协议.基本上使用者可以”为所欲为”,可以自由的使用,修改源代码,也可以将修改后的代码作为开源或者专有软件再发布. 但”为所欲为”的前提当你发布使 ...

  10. 时间序列分解算法:STL

    1. 详解 STL (Seasonal-Trend decomposition procedure based on Loess) [1] 为时序分解中一种常见的算法,基于LOESS将某时刻的数据\( ...