Series Spring Boot: Spring Boot 0: Làm chủ Spring Boot, Zero to HeroSeries Spring Boot từ con số 0

Series Spring Core: tại đây

Dưới đây là Series Spring Thymeleaf

  1. Thymeleaf là gì? So sánh JSP, JSF với Thymeleaf
  2. Code ví dụ Spring MVC Thymeleaf Hello – dùng XML config
  3. Code ví dụ Spring MVC Thymeleaf Hello – dùng annotation config
  4. Submit form với Thymeleaf, Code ví dụ Spring Thymeleaf Form
  5. Code ví dụ hiển thị List, Set, Map với Thymeleaf
  6. Code ví dụ đa ngôn ngữ với Thymeleaf Internationalization / i18n
  7. Code ví dụ gửi email – gmail với Thymeleaf + Spring

Xử lý Form với Spring Thymeleaf

Các công nghệ sử dụng trong bài viết này

  • Spring 5.0.2.RELEASE
  • Thymeleaf 3.0.9.RELEASE
  • Thymeleaf-spring5 3.0.9.RELEASE
  • Maven
  • JDK 1.8

Tạo Maven project

Submit form với Thymeleaf, Code ví dụ Spring Thymeleaf Form

Thư viện sử dụng:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>stackjava.com</groupId>
  <artifactId>SpringThymeleaf</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
  <properties>
    <spring.version>5.0.2.RELEASE</spring.version>
    <thymeleaf.version>3.0.9.RELEASE</thymeleaf.version>
  </properties>
  <dependencies>
    <!-- Spring -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>
    <!-- Thymeleaf -->
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf</artifactId>
      <version>${thymeleaf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.thymeleaf</groupId>
      <artifactId>thymeleaf-spring5</artifactId>
      <version>${thymeleaf.version}</version>
    </dependency>
  </dependencies>
</project>

File Spring config:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
  xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd">
  <context:component-scan base-package="stackjava.com.springthymeleaf" />
  <bean id="templateResolver"
    class="org.thymeleaf.spring5.templateresolver.SpringResourceTemplateResolver">
    <property name="prefix" value="/WEB-INF/templates/" />
    <property name="suffix" value=".html" />
    <property name="templateMode" value="HTML5" />
    <property name="cacheable" value="false" />
  </bean>
  <bean id="templateEngine" class="org.thymeleaf.spring5.SpringTemplateEngine">
    <property name="templateResolver" ref="templateResolver" />
  </bean>
  <bean class="org.thymeleaf.spring5.view.ThymeleafViewResolver">
    <property name="templateEngine" ref="templateEngine" />
  </bean>
</beans>

File web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">
  <display-name>SpringThymeleaf</display-name>
  <servlet>
    <servlet-name>spring-mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>spring-mvc</servlet-name>
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

File entities:

package stackjava.com.springthymeleaf.entities;
public class Employee {
  private int id;
  private String name;
  private String address;
  private String email;
  private String gender;
  private String[] favorites;
  private String position;
  // getter-setter
}

File Controller

package stackjava.com.springthymeleaf.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import stackjava.com.springthymeleaf.entities.Employee;
@Controller
public class EmployeeController {
  @RequestMapping(value = { "/", "/addEmployee" }, method = RequestMethod.GET)
  public String addEmployee(Model model) {
    model.addAttribute("employee", new Employee());
    List<String> listFavorite = new ArrayList<String>();
    listFavorite.add("Swimming");
    listFavorite.add("Listening music");
    listFavorite.add("Walking");
    listFavorite.add("Watching movie");
    listFavorite.add("Reading comic");
    model.addAttribute("listFavorite", listFavorite);
    List<String> listPosition = new ArrayList<String>();
    listPosition.add("Developer");
    listPosition.add("Designer");
    listPosition.add("Tester");
    listPosition.add("QA");
    model.addAttribute("listFavorite", listFavorite);
    model.addAttribute("listPosition", listPosition);
    return "add-employee";
  }
  @RequestMapping(value = "/addEmployee", method = RequestMethod.POST)
  public String doAddEmployee(@ModelAttribute("employee") Employee employee, ModelMap modelMap) {
    modelMap.addAttribute("employee", employee);
    return "view-employee";
  }
}

File view:

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring MVC + Thymeleaf</title>
</head>
<body>
  <h2>Add Employee</h2>
  <form th:action="@{/addEmployee}" th:object="${employee}" method="post">
    <table>
      <tr>
        <td>Id</td>
        <td><input th:field="*{id}" /></td>
      </tr>
      <tr>
        <td>Name</td>
        <td><input th:field="*{name}" /></td>
      </tr>
      <tr>
        <td>Addess</td>
        <td><textarea th:field="*{address}" /></td>
      </tr>
      <tr>
        <td>Email</td>
        <td><input th:field="*{email}" /></td>
      </tr>
      <tr>
        <td>Gender</td>
        <td>
            <input type="radio" th:field="*{gender}" th:value="male" />
            <label th:text="male" />
            <input type="radio" th:field="*{gender}" th:value="female" />
            <label th:text="female" />
        </td>
      </tr>
      <tr>
        <td>Favorite</td>
        <td>
          <ul style="list-style-type: none;">
            <li th:each="fa : ${listFavorite}">
              <input type="checkbox" 
                  th:field="*{favorites}"
                  th:value="${fa}" />
              <label th:text="${fa}"></label>
            </li>
          </ul>
        </td>
      </tr>
      <tr>
        <td>Position</td>
        <td>
                  <select th:field="*{position}">
                      <option value=""></option>
                      <option th:each="ps : ${listPosition}"
                          th:value="${ps}" th:text="${ps}"></option>
                  </select>
                </td>
      </tr>
      <tr>
        <td colspan="2"><input type="submit" value="Submit" /></td>
      </tr>
    </table>
  </form>
</body>
</html>
  • th:action=”@{/addEmployee}”: khai báo action, @{/addEmployee} tương tự với việc mapping url trong spring mvc
  • th:object=”${employee}” tương tự với modelAttribute=“customer” trong spring mvc form
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Spring MVC + Thymeleaf</title>
</head>
<body>
  <h2>Employee</h2>
  <table>
    <tr>
      <td>Id:</td>
      <td><p th:text="${employee.id}" /></td>
    </tr>
    <tr>
      <td>Name:</td>
      <td><p th:text="${employee.name}" /></td>
    </tr>
    <tr>
      <td>Address:</td>
      <td><p th:text="${employee.address}" /></td>
    </tr>
    <tr>
      <td>Email:</td>
      <td><p th:text="${employee.email}" /></td>
    </tr>
    <tr>
      <td>Gender:</td>
      <td><p th:text="${employee.gender}" /></td>
    </tr>
    <tr>
      <td>Favorite:</td>
      <td>
        <p th:each="fa: ${employee.favorites}" th:text="${fa}"></p>
      </td>
    </tr>
    <tr>
      <td>Position:</td>
      <td><p th:text="${employee.position}" /></td>
    </tr>
  </table>
</body>
</html>

Demo:

Code ví dụ Spring Thymeleaf Form, Xử lý Form Spring-Thymeleaf

Submit form với Thymeleaf, Code ví dụ Spring Thymeleaf Form

Okay, Done!
Download code ví dụ trên tại đây


Loạt bài chủ đề Java trên trang stackjava.com bản quyền thuộc thầy Trần Hữu Cương. Bài viết đăng trên blog Techmaster được sự đồng ý của tác giả.

Thầy Trần Hữu Cương đã và đang tham gia giảng dạy tại Techmater khoá Lộ trình Java Spring Boot Full Stack

Link gốc bài viết tại đây.