SpringBoot项目基础架构

以下是一个简单的示例,展示了如何使用Spring Boot实现前后端分离项目,包含代码讲解和详细注释。

  1. 创建项目:

创建一个空的Spring Boot项目。

  1. 设置依赖:

使用你喜欢的构建工具(例如Maven)将以下依赖添加到项目的pom.xml文件中:


<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-web</artifactId>

</dependency>

 

<!-- Spring Data JPA 依赖 -->

<dependency>

    <groupId>org.springframework.boot</groupId>

    <artifactId>spring-boot-starter-data-jpa</artifactId>

</dependency>

 

<!-- H2 内存数据库依赖 -->

<dependency>

    <groupId>com.h2database</groupId>

    <artifactId>h2</artifactId>

    <scope>runtime</scope>

</dependency>

这些依赖包含了Spring Boot、Spring MVC和Spring Data JPA相关的库。

  1. 创建数据库表:

使用数据库管理工具创建一个名为"student"的表,包含id、name、age和score字段。

  1. 创建实体类:

创建一个名为Student的实体类,添加相应的注解,使其能够与数据库表进行映射。


@Entity

@Table(name = "student")

public class Student {
    @Id

    @GeneratedValue(strategy = GenerationType.IDENTITY)

    private Long id;

    

    private String name;

    

    private int age;

    

    private double score;

    

    // 省略getter和setter方法

}

  1. 创建数据访问层(Repository):

创建一个名为StudentRepository的接口,继承自JpaRepository,用于对数据库表进行增删改查操作。


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

  1. 创建业务逻辑层(Service):

创建一个名为StudentService的接口,定义一些学生信息相关的业务逻辑方法,如添加学生、删除学生、修改学生信息等。


public interface StudentService {
    Student addStudent(Student student);

    void deleteStudent(Long id);

    Student updateStudent(Student student);

    List<Student> getAllStudents();

}

  1. 实现业务逻辑层(Service):

创建一个名为StudentServiceImpl的类,实现StudentService接口,并注入StudentRepository,用于对数据库进行操作。


@Service

public class StudentServiceImpl implements StudentService {
    

    private final StudentRepository studentRepository;

    

    public StudentServiceImpl(StudentRepository studentRepository) {
        this.studentRepository = studentRepository;

    }

    

    @Override

    public Student addStudent(Student student) {
        return studentRepository.save(student);

    }

    

    @Override

    public void deleteStudent(Long id) {
        studentRepository.deleteById(id);

    }

    

    @Override

    public Student updateStudent(Student student) {
        return studentRepository.save(student);

    }

    

    @Override

    public List<Student> getAllStudents() {
        return studentRepository.findAll();

    }

}

  1. 创建控制器层(Controller):

创建一个名为StudentController的类,添加@RestController注解,并注入StudentService,用于处理前端的请求。


@RestController

@RequestMapping("/api/students")

public class StudentController {
    

    private final StudentService studentService;

    

    public StudentController(StudentService studentService) {
        this.studentService = studentService;

    }

    

    @PostMapping

    public ResponseEntity<Student> addStudent(@RequestBody Student student) {
        Student newStudent = studentService.addStudent(student);

        return ResponseEntity.ok(newStudent);

    }

    

    @DeleteMapping("/{id}")

    public ResponseEntity<Void> deleteStudent(@PathVariable Long id) {
        studentService.deleteStudent(id);

        return ResponseEntity.noContent().build();

    }

    

    @PutMapping("/{id}")

    public ResponseEntity<Student> updateStudent(@PathVariable Long id, @RequestBody Student student) {
        student.setId(id);

        Student updatedStudent = studentService.updateStudent(student);

        return ResponseEntity.ok(updatedStudent);

    }

    

    @GetMapping

    public ResponseEntity<List<Student>> getAllStudents() {
        List<Student> students = studentService.getAllStudents();

        return ResponseEntity.ok(students);

    }

}

  1. 前端实现:

在resources/static目录下创建一个index.html文件,编写HTML页面的结构和样式,并使用JavaScript发起与后端的接口交互。


<!DOCTYPE html>

<html>

<head>

    <meta charset="UTF-8">

    <title>Student Management System</title>

</head>

<body>

    <h1>Students</h1>

    

    <div>

        <table>

            <thead>

                <tr>

                    <th>ID</th>

                    <th>Name</th>

                    <th>Age</th>

                    <th>Score</th>

                </tr>

            </thead>

            <tbody id="studentsTableBody">

                <!-- 学生信息将会通过JavaScript动态添加到这里 -->

            </tbody>

        </table>

    </div>

    

    <form id="addStudentForm">

        <h2>Add Student</h2>

        <div>

            <label for="name">Name:</label>

            <input type="text" id="name" name="name" required>

        </div>

        <div>

            <label for="age">Age:</label>

            <input type="number" id="age" name="age" required>

        </div>

        <div>

            <label for="score">Score:</label>

            <input type="number" id="score" name="score" required>

        </div>

        <div>

            <button type="submit">Add</button>

        </div>

    </form>

    

    <script>

        document.addEventListener('DOMContentLoaded', function() {
            // 在页面加载完毕后获取学生数据并渲染到表格中

            fetchStudents();

            

            // 处理添加学生表单的提交事件

            document.getElementById('addStudentForm').addEventListener('submit', function(event) {
                event.preventDefault(); // 阻止表单提交的默认行为

                

                // 从表单中获取输入数据

                const name = document.getElementById('name').value;

                const age = document.getElementById('age').value;

                const score = document.getElementById('score').value;

                

                // 创建一个新的学生对象

                const newStudent = {
                    name: name,

                    age: age,

                    score: score

                };

                

                // 发起POST请求,将新学生添加到后端数据库

                addStudent(newStudent);

                

                // 清空表单

                document.getElementById('name').value = '';

                document.getElementById('age').value = '';

                document.getElementById('score').value = '';

            });

        });

        

        function fetchStudents() {
            fetch('/api/students')

                .then(response => response.json())

                .then(students => renderStudentsTable(students));

        }

        

        function renderStudentsTable(students) {
            const tableBody = document.getElementById('studentsTableBody');

            tableBody.innerHTML = ''; // 清空表格

            

            students.forEach(student => {
                const tr = document.createElement('tr');

                

                const idTd = document.createElement('td');

                idTd.textContent = student.id;

                tr.appendChild(idTd);

                

                const nameTd = document.createElement('td');

                nameTd.textContent = student.name;

                tr.appendChild(nameTd);

                

                const ageTd = document.createElement('td');

                ageTd.textContent = student.age;

                tr.appendChild(ageTd);

                

                const scoreTd = document.createElement('td');

                scoreTd.textContent = student.score;

                tr.appendChild(scoreTd);

                

                tableBody.appendChild(tr);

            });

        }

        

        function addStudent(student) {
            fetch('/api/students', {
                method: 'POST',

                headers: {
                    'Content-Type': 'application/json'

                },

                body: JSON.stringify(student)

            })

            .then(response => response.json())

            .then(student => {
                // 添加成功后重新获取学生数据并渲染表格

                fetchStudents();

            });

        }

    </script>

</body>

</html>

  1. 启动项目:

运行项目,启动Spring Boot应用程序。

  1. 前后端交互:

使用浏览器访问前端页面,触发相应的请求,后端会根据URL和请求方式调用相应的方法,完成相应的业务逻辑,并将结果返回给前端。

在本例中,访问http://localhost:8080,即可看到学生信息的表格。可以通过表单添加学生,添加成功后表格会刷新显示最新的学生信息。
————————————————
版权声明:本文为CSDN博主「KingDol6080」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/m0_68856746/article/details/131364988

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值