Spring Boot2 series of tutorials (xii) | integration thymeleaf

Foreword

If that, today introduced Thymeleaf, and integrate Thymeleaf develop a rudimentary version of the Student Information Management System.

SpringBoot provides a number of template engine, contains Freemarker, Groovy, Thymeleaf, Velocity and Mustache, SpringBoot recommended to use as a template engine Thymeleaf, because Thymeleaf provides the perfect SpringMVC support. Thymeleaf is a new generation of Java template engine, it is recommended after Spring 4.

What is a template engine?

Thymeleaf is a template language. What's template language or template engines? Common language template contains the following concepts: data (Data), the template (Template), template engine (Template Engine) and the resulting document (Result Documents).

  • Data
    Data are expressions and vector information may be symbols, words, figures, voice, images and video. Data and information are inseparable, the expression data information, the data information is a connotation. Does not make sense data itself, the data only when the impact on the real behavior become information.
  • Template
    template, a blueprint that has nothing to do with a type of class. When using a template compiler will instantiate a template argument according to the template, to obtain a type-specific classes.
  • Template engine
    template engine (here especially for Web development template engine) is to make the user interface and business data (content) resulting from the separation, it can generate a document-specific format for the site will generate a template engine standard HTML document.
  • The results document
    a particular format documents, such as the site for the template engine will generate a standard HTML document.

Template Language wide range of uses, common uses are as follows:

  • Page rendering
  • Document Generation
  • Code Generation
  • All "Data + text template =" application scenarios

Thymeleaf Profile

Thymeleaf is a Java class library, it is a xml / xhtml / html5 template engine, it can be used as the View layer of the MVC web application.

Thymeleaf also offers additional modules to integrate with SpringMVC, so we can use Thymeleaf completely replace the JSP.

Thymeleaf grammar

Blog information: http: //www.cnblogs.com/nuoyiamy/p/5591559.html
official document: http: //www.thymeleaf.org/documentation.html

SpringBoot integration Thymeleaf

The following integration Thymeleaf develop a rudimentary version of student information management system SpringBoot.

1, ready to work

  • IDEA
  • JDK1.8
  • SpringBoot2.1.3

2, pom.xml depends

<dependencies>
        <!-- JPA 数据访问 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <!-- thymeleaf 模板引擎 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!-- web 启动类 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <!-- mysql 数据库连接类 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
</dependencies>

3, application.yaml configuration file

spring:
  # 数据库相关
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8&serverTimezone=UTC&useSSL=true
    username: root
    password: 123456
  # jpa 相关
  jpa:
    hibernate:
      ddl-auto: update   # ddl-auto: 第一次启动项目设为 create 表示每次都重新建表,之后设置为 update
    show-sql: true

4, the entity class

@Data
@Entity
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    @Id
    @GeneratedValue
    /**
     * 主键
     */
    private Long id;

    /**
     * 主键
     */
    private Long studentId;

    /**
     * 姓名
     */
    private String name;

    /**
     * 年龄
     */
    private Integer age;

    /**
     * 专业
     */
    private String major;

    /**
     * 宿舍
     */
    private String dormitory;

    /**
     * 籍贯
     */
    private String city;

    /*@Temporal(TemporalType.TIMESTAMP)//将时间戳,转换成年月日时分秒的日期格式
    @Column(name = "create_time",insertable = false, updatable=false, columnDefinition = "timestamp default current_timestamp comment '注册时间'")
    private Date createDate;

    @Temporal(TemporalType.TIMESTAMP)//将时间戳,转换成年月日时分秒的日期格式
    @Column(name = "update_time",insertable = false, updatable=true, columnDefinition = "timestamp default current_timestamp comment '修改时间'")
    private Date updateDate;*/

}

5, dao layer

@Repository
public interface StudentRepository extends JpaRepository<Student, Long> {
}

6, service layer

public interface StudentService {

    List<Student> findStudentList();

    Student findStudentById(Long id);

    Student saveStudent(Student student);

    Student updateStudent(Student student);

    void deleteStudentById(Long id);

}

Implementing Classes:

@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentRepository studentRepository;

    /**
     * 查询所有学生信息列表
     * @return
     */
    @Override
    public List<Student> findStudentList() {
        Sort sort = new Sort(Direction.ASC,"id");
        return studentRepository.findAll(sort);
    }

    /**
     * 根据 id 查询单个学生信息
     * @param id
     * @return
     */
    @Override
    public Student findStudentById(Long id) {
        return studentRepository.findById(id).get();
    }

    /**
     * 保存学生信息
     * @param student
     * @return
     */
    @Override
    public Student saveStudent(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 更新学生信息
     * @param student
     * @return
     */
    @Override
    public Student updateStudent(Student student) {
        return studentRepository.save(student);
    }

    /**
     * 根据 id 删除学生信息
     * @param id
     * @return
     */
    @Override
    public void deleteStudentById(Long id) {
        studentRepository.deleteById(id);
    }
}

7, controller layer (Thymeleaf) using

controller layer view point Thymeleaf:

@Controller
@RequestMapping("/student")
public class StudentController {

    @Autowired
    private StudentService studentService;

    /**
     * 获取学生信息列表
     * @param map
     * @return
     */
    @GetMapping("/list")
    public String findStudentList(ModelMap map) {
        map.addAttribute("studentList",studentService.findStudentList());
        return "studentList";
    }

    /**
     * 获取保存 student 表单
     */
    @GetMapping(value = "/create")
    public String createStudentForm(ModelMap map) {
        map.addAttribute("student", new Student());
        map.addAttribute("action", "create");
        return "studentForm";
    }

    /**
     * 保存学生信息
     * @param student
     * @return
     */
    @PostMapping(value = "/create")
    public String saveStudent(@ModelAttribute Student student) {
        studentService.saveStudent(student);
        return "redirect:/student/list";
    }

    /**
     * 根据 id 获取 student 表单,编辑后提交更新
     * @param id
     * @param map
     * @return
     */
    @GetMapping(value = "/update/{id}")
    public String edit(@PathVariable Long id, ModelMap map) {
        map.addAttribute("student", studentService.findStudentById(id));
        map.addAttribute("action", "update");
        return "studentForm";
    }

    /**
     * 更新学生信息
     * @param student
     * @return
     */
    @PostMapping(value = "/update")
    public String updateStudent(@ModelAttribute Student student) {
        studentService.updateStudent(student);
        return "redirect:/student/list";
    }

    /**
     * 删除学生信息
     * @param id
     * @return
     */
    @GetMapping(value = "/delete/{id}")
    public String deleteStudentById(@PathVariable Long id) {
        studentService.deleteStudentById(id);
        return "redirect:/student/list";
    }
}

Under Simply put, ModelMap object to bind data to the view. return string corresponding template directory name in the resources / templates of. @ModelAttribute annotations are used to obtain the data page Form form submission, and bind to the Student Data Objects.

8, studentForm form

It defines a Form form is used to register or modify student information.

<form th:action="@{/student/{action}(action=${action})}" method="post" class="form-horizontal">

        <div class="form-group">
            <label for="student_Id" class="col-sm-2 control-label">学号:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_Id" name="name" th:value="${student.studentId}"
                       th:field="*{student.studentId}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_name" class="col-sm-2 control-label">姓名:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_name" name="name" th:value="${student.name}"
                       th:field="*{student.name}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_age" class="col-sm-2 control-label">年龄:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_age" name="name" th:value="${student.age}"
                       th:field="*{student.age}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_major" class="col-sm-2 control-label">专业:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_major" name="name" th:value="${student.major}"
                       th:field="*{student.major}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_dormitory" class="col-sm-2 control-label">宿舍:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_dormitory" name="name" th:value="${student.dormitory}"
                       th:field="*{student.dormitory}"/>
            </div>
        </div>

        <div class="form-group">
            <label for="student_city" class="col-sm-2 control-label">籍贯:</label>
            <div class="col-xs-4">
                <input type="text" class="form-control" id="student_city" name="writer" th:value="${student.city}"
                       th:field="*{student.city}"/>
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-3 col-sm-10">
                <input class="btn btn-primary" type="submit" value="提交"/>&nbsp;&nbsp;
                <input class="btn" type="button" value="返回" onclick="history.back()"/>
            </div>
        </div>
    </form>

9, studentList student list

For displaying student information:

<table class="table table-hover table-condensed">
        <legend>
            <strong>学生信息列表</strong>
        </legend>
        <thead>
        <tr>
            <th>学号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>专业</th>
            <th>宿舍</th>
            <th>籍贯</th>
            <th>管理</th>
        </tr>
        </thead>
        <tbody>
        <tr th:each="student : ${studentList}">
            <th scope="row" th:text="${student.studentId}"></th>
            <td><a th:href="@{/student/update/{studentId}(studentId=${student.id})}" th:text="${student.name}"></a></td>
            <td th:text="${student.age}"></td>
            <td th:text="${student.major}"></td>
            <td th:text="${student.dormitory}"></td>
            <td th:text="${student.city}"></td>
            <td><a class="btn btn-danger" th:href="@{/student/delete/{studentId}(studentId=${student.id})}">删除</a></td>
        </tr>
        </tbody>
    </table>

Results page

List page: Click the button to register student information

The initial page

Registration / modify student information page: Submit to save the point of student information to the database and return a list of page

Registration / modify student information page

There are data list page: Click on a name to jump to the registration / modification may modify student information page, click Delete to delete student information

List page

Source download

github address: https: //github.com/turoDog/Demo/tree/master/springboot_thymeleaf_demo

At last

If you see here, that you liked this article, please forward, thumbs up. Micro-channel search " a good basket case ", after concerns reply " 1024 " will give you a complete set of java tutorial.

Tutorial excerpt
A good basket

Guess you like

Origin www.cnblogs.com/nasus/p/12149810.html