【java】springboot前后端分离简单案例

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

 

1. 创建项目:

创建一个空的Spring Boot项目。

 

2. 设置依赖:

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

```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相关的库。

 

3. 创建数据库表:

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

 

4. 创建实体类:

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

```java

@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方法

}

```

 

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

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

```java

public interface StudentRepository extends JpaRepository<Student, Long> {

}

```

 

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

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

```java

public interface StudentService {

    Student addStudent(Student student);

    void deleteStudent(Long id);

    Student updateStudent(Student student);

    List<Student> getAllStudents();

}

```

 

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

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

```java

@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();

    }

}

```

 

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

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

```java

@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);

    }

}

```

 

9. 前端实现:

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

 

```html

<!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>

```

 

11. 启动项目:

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

 

12. 前后端交互:

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

在本例中,访问http://localhost:8080,即可看到学生信息的表格。可以通过表单添加学生,添加成功后表格会刷新显示最新的学生信息。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
前后端分离的架构中,前端和后端是独立部署和运行的,因此需要在后端项目中使用spring-boot-starter-actuator来对后端应用进行监控和管理。前端项目可以通过HTTP接口调用actuator的端点来获取应用程序的信息。 首先,你需要在后端Spring Boot项目中添加spring-boot-starter-actuator的依赖。在你的pom.xml文件中,添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-actuator</artifactId> </dependency> ``` 然后,你需要在应用程序的配置文件(例如application.properties或application.yml)中配置actuator的相关属性。例如,你可以设置管理端点的访问路径和权限: ```properties # 设置管理端点的访问路径 management.endpoints.web.base-path=/actuator # 开启所有的管理端点,默认只开启了/health和/info management.endpoints.web.exposure.include=* ``` 配置完成后,你可以启动后端应用程序,并通过HTTP请求访问actuator提供的各种端点来获取应用程序的信息。例如: - `/actuator/health`:应用程序的健康状况 - `/actuator/info`:应用程序的信息 - `/actuator/metrics`:度量指标信息 - `/actuator/env`:运行时环境信息 你可以根据具体需求,选择性地暴露和配置这些端点。同时,你还可以自定义自己的管理端点,以满足特定的监控和管理需求。 在前端项目中,你可以通过发送HTTP请求来调用这些管理端点,获取后端应用程序的信息,从而实现前端对后端应用程序的监控和管理功能。 希望这些信息对你有帮助!如果还有其他问题,请随时提问。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值