《Spring boot从入门到实战》第七章习题答案

7.5 本章练习

  1. 创建一个Spring Boot项目,使用Thymeleaf页面模板引擎和JdbcTemplate数据持久化框架实现完整的学生信息管理模块。

答案:

  1. application.properties 配置数据库

    spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.primary.jdbc-url=jdbc:mysql://127.0.0.1:3306/test?useSSL=false&serverTimezone=UTC
    spring.datasource.primary.username=root
    spring.datasource.primary.password=123456
    spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.secondary.jdbc-url=jdbc:mysql://127.0.0.1:3306/dp_database?useSSL=false&serverTimezone=UTC
    spring.datasource.secondary.username=root
    spring.datasource.secondary.password=123456

    1. JdbcTemplate 配置

    package com.example.demo.config;

    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.jdbc.DataSourceBuilder;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.jdbc.core.JdbcTemplate;

    import javax.sql.DataSource;

    @Configuration
    public class DataSourceConfig {

    复制代码
     @Primary
     @Bean(name = "primaryDataSource")
     @Qualifier("primaryDataSource")
     @ConfigurationProperties("spring.datasource.primary")
     public DataSource primaryDataSource() {
         return DataSourceBuilder.create().build();
     }
    
     @Bean(name = "secondaryDataSource")
     @Qualifier("secondaryDataSource")
     @ConfigurationProperties("spring.datasource.secondary")
     public DataSource secondaryDataSource() {
         return DataSourceBuilder.create().build();
     }
    
     @Bean(name = "primaryJdbcTemplate")
     public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {
         return new JdbcTemplate(dataSource);
     }
    
     @Bean(name = "secondaryJdbcTemplate")
     public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {
         return new JdbcTemplate(dataSource);
     }

    }

  2. 学生实体类 Student.java

    package com.example.demo.bean;

    public class Student {

    复制代码
     private Long id;
     private String name;
     private Integer sex;
     private Integer age;
    
     public Student() {
     }
    
     public Student(String name, int sex, int age) {
         this.name = name;
         this.sex = sex;
         this.age = age;
     }
    
     @Override
     public String toString() {
         return "Student{" +
                 "id=" + id +
                 ", name='" + name + '\'' +
                 ", sex=" + sex +
                 ", age=" + age +
                 '}';
     }
    
     public Long getId() {
         return id;
     }
    
     public void setId(Long id) {
         this.id = id;
     }
    
     public String getName() {
         return name;
     }
    
     public void setName(String name) {
         this.name = name;
     }
    
     public Integer getSex() {
         return sex;
     }
    
     public void setSex(int sex) {
         this.sex = sex;
     }
    
     public Integer getAge() {
         return age;
     }
    
     public void setAge(int age) {
         this.age = age;
     }

    }

  3. StudentController 控制器 创建 StudentController 类,处理学生管理的 HTTP 请求。

    package com.example.demo.controller;

    import com.example.demo.bean.Student;
    import com.example.demo.service.StudentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;

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

    复制代码
     @Autowired
     private StudentService studentService;
    
     @GetMapping("/")
     public String getAllStudents(Model model) {
         model.addAttribute("students", studentService.listAllStudent());
         return "students/list";
     }
    
     @GetMapping("/add")
     public String showAddForm(Model model) {
         model.addAttribute("student", new Student());
         return "students/add";
     }
    
     @PostMapping("/add")
     public String addStudent(@ModelAttribute Student student) {
         studentService.insertStudent(student);
         return "redirect:/students/";
     }
    
     @GetMapping("/edit/{id}")
     public String showEditForm(@PathVariable Long id, Model model) {
         Student student = studentService.getStudentById(id);
         model.addAttribute("student", student);
         return "students/edit";
     }
    
     @PostMapping("/edit/{id}")
     public String updateStudent(@PathVariable Long id, @ModelAttribute Student student) {
         student.setId(id);
         studentService.updateStudent(student);
         return "redirect:/students/";
     }
    
     @GetMapping("/delete/{id}")
     public String deleteStudent(@PathVariable Long id) {
         studentService.deleteStudent(id);
         return "redirect:/students/";
     }

    }

  4. StudentService 服务类 创建 StudentService 类,用于业务逻辑处理。

    package com.example.demo.service;

    import com.example.demo.bean.Student;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Service;

    import java.util.List;

    @Service
    public class StudentService {

    复制代码
     @Autowired
     @Qualifier("primaryJdbcTemplate")
     private JdbcTemplate jdbcTemplate;
    
     public List<Student> listAllStudent(){
         String sql = "select * from student";
         return jdbcTemplate.query(sql, new BeanPropertyRowMapper<Student>(Student.class));
     }
    
     public Student getStudentById(Long id){
         String sql = "select * from student where id=?";
         return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Student.class));
     }
    
     public void insertStudent(Student student){
         String sql = "insert into student(id, name, age, sex) values(?,?,?,?)";
         jdbcTemplate.update(sql,student.getId(),student.getName(),student.getAge(),student.getSex());
     }
    
     public void updateStudent(Student student){
         String sql = "update student set name=?,age=?,sex=? where id=?";
         jdbcTemplate.update(sql,student.getName(),student.getAge(),student.getSex(),student.getId());
     }
    
     public void deleteStudent(Long id){
         String sql = "delete from student where id=?";
         jdbcTemplate.update(sql,id);
     }

    }

  5. Thymeleaf 页面 创建页面模板来展示学生列表、添加、编辑学生等功能。

list.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>学生信息管理</title>
</head>
<body>
<h1>学生信息</h1>
<table>
    <thead>
    <tr>
        <th>ID</th>
        <th>姓名</th>
        <th>年龄</th>
        <th>性别</th>
        <th>操作</th>
    </tr>
    </thead>
    <tbody>
    <tr th:each="student : ${students}">
        <td th:text="${student.id}"></td>
        <td th:text="${student.name}"></td>
        <td th:text="${student.age}"></td>
        <td th:text="${student.sex}"></td>
        <td>
            <a th:href="@{/students/edit/{id}(id=${student.id})}">编辑</a> |
            <a th:href="@{/students/delete/{id}(id=${student.id})}">删除</a>
        </td>
    </tr>
    </tbody>
</table>
<a href="/students/add">添加学生</a>
</body>
</html>

add.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>添加学生</title>
</head>
<body>
<h1>添加学生</h1>
<form action="#" th:action="@{/students/add}" th:object="${student}" method="post">
    <label>姓名:</label>
    <input type="text" th:field="*{name}"/><br/>
    <label>年龄:</label>
    <input type="number" th:field="*{age}"/><br/>
    <label>性别:</label>
    <input type="number" th:field="*{sex}"/><br/>
    <button type="submit">提交</button>
</form>
<a href="/students/">返回</a>
</body>
</html>

edit.html

复制代码
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>编辑学生</title>
</head>
<body>
<h1>编辑学生</h1>
<form action="#" th:action="@{/students/edit/{id}(id=${student.id})}" th:object="${student}" method="post">
    <label>姓名:</label>
    <input type="text" th:field="*{name}"/><br/>
    <label>年龄:</label>
    <input type="number" th:field="*{age}"/><br/>
    <label>性别:</label>
    <input type="number" th:field="*{sex}"/><br/>
    <button type="submit">提交</button>
</form>
<a href="/students/">返回</a>
</body>
</html>
  1. 测试 启动 Spring Boot 应用,访问:
相关推荐
fen_fen15 小时前
Oracle建表语句示例
数据库·oracle
qq_2975746715 小时前
【实战教程】SpringBoot 实现多文件批量下载并打包为 ZIP 压缩包
java·spring boot·后端
砚边数影17 小时前
数据可视化入门:Matplotlib 基础语法与折线图绘制
数据库·信息可视化·matplotlib·数据可视化·kingbase·数据库平替用金仓·金仓数据库
orange_tt17 小时前
Djiango配置Celery
数据库·sqlite
云小逸18 小时前
【nmap源码学习】 Nmap网络扫描工具深度解析:从基础参数到核心扫描逻辑
网络·数据库·学习
肉包_51118 小时前
两个数据库互锁,用全局变量互锁会偶发软件卡死
开发语言·数据库·c++
霖霖总总18 小时前
[小技巧64]深入解析 MySQL InnoDB 的 Checkpoint 机制:原理、类型与调优
数据库·mysql
tb_first19 小时前
LangChain4j简单入门
java·spring boot·langchain4j
此刻你19 小时前
常用的 SQL 语句
数据库·sql·oracle
それども20 小时前
分库分表的事务问题 - 怎么实现事务
java·数据库·mysql