在本教程中,我们将使用 React 作为前端,使用Spring Boot作为后端 来创建一个简单的“单页应用程序” 。
React 用于在前端构建用户界面(UI)。
Spring Boot 在开发 RESTful Web 服务和微服务方面很受欢迎。
众所周知,React 是一个基于 JavaScript 的库,不具备发出 HTTP 请求的能力;因此,我们需要使用第三方库来实现这一点。
有很多库可用于对 React 应用程序进行 HTTP 调用。下面列出了其中的一些。
- Axios
- Fetch
- Superagent
- React-axios
- Use-http
- React-request
在本示例教程中,我们将使用 Axios HTTP 库进行 HTTP Get REST API 调用。
5.先决条件
- 基本熟悉 HTML & CSS
- JavaScript和编程的基本知识
- Spring Boot 基础知识
- ReactJS 基础知识
- 全局安装 Node.js 和 npm
我们将建造什么?
我们将构建两个项目:
- sprintboot-backend (server) – 开发 REST API
- react-frontend (client) – 使用 REST API
客户端-服务器架构
1.开发Spring Boot后端应用
我们将使用Spring Data JPA开发存储库层,并使用 H2 内存数据库来存储数据。
1. 创建一个 Spring Boot 应用程序
有很多方法可以创建 Spring Boot 应用程序。您可以参考以下文章来创建 Spring Boot 应用程序。
>> 使用 Spring Initializer创建 Spring Boot 项目
>> 在 Spring Tool Suite [STS] 中创建 Spring Boot 项目
2.添加maven依赖
<?xml version="1.0" encoding="UTF-8"?>
<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>com.blogspot.javabyrajasekhar</groupId>
<artifactId>SpringbootCommandLineRunner</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>SpringbootCommandLineRunner</name>
<description>SpringbootCommandLineRunner</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
创建 JPA 实体 - User.java
在net.javaguides.springboot包中 创建一个名为model的新包,然后在模型包中创建User类,其内容如下 -
package net.javaguides.springboot.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "users")
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
private String email;
public User() {
}
public User(String firstName, String lastName, String email) {
super();
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
创建 Spring Data JPA 存储库 - UserRepository.java
在net.javaguides.springboot包中 创建一个名为repository的新包,然后在repository包中创建以下接口 -
package net.javaguides.springboot.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import net.javaguides.springboot.model.User;
@Repository
public interface UserRepository extends JpaRepository<User, Long>{
}
带有 REST API 的 Spring 控制器 - /api/users
让我们创建一个UserController类并向其中添加以下代码:
package net.javaguides.springboot.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;
@CrossOrigin
@RestController
@RequestMapping("api/")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("users")
public List < User > getUsers() {
return this.userRepository.findAll();
}
}
请注意,我们添加了以下代码行以避免 CORS 问题:
@CrossOrigin(origins = "http://localhost:3000")
运行 Spring Boot 应用程序并测试 Rest API
让我们在应用程序启动时在用户表 中插入几条记录。
让我们从 IDE 运行这个 Spring Boot 应用程序 -> 右键单击 -> 运行方式 -> Java 应用程序:
package net.javaguides.springboot;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import net.javaguides.springboot.model.User;
import net.javaguides.springboot.repository.UserRepository;
@SpringBootApplication
public class SpringbootBackendApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(SpringbootBackendApplication.class, args);
}
@Autowired
private UserRepository userRepository;
@Override
public void run(String...args) throws Exception {
this.userRepository.save(new User("Ramesh", "Fadatare", "ramesh@gmail.com"));
this.userRepository.save(new User("Tom", "Cruise", "tom@gmail.com"));
this.userRepository.save(new User("Tony", "Stark", "tony@gmail.com"));
}
}
在浏览器中点击这个“ http://localhost:8080/api/users ”链接将流行的用户列表作为 JSON:
构建 React JS 前端应用程序
让我们继续创建一个 React 应用程序来使用/api/users REST API。
1 - 使用 Create React App 创建一个 React UI
Create React App CLI 工具是官方支持 的创建单页 React 应用程序的方法。它提供了一个没有配置的现代构建设置。
要创建新应用程序,您可以选择以下方法之一:
使用 npx
npx create-react-app react-frontend
使用 npm
npm init react-app react-frontend
npm init 在 npm 6+ 中可用
使用纱线
yarn create react-app react-frontend
运行这些命令中的任何一个都会在当前文件夹中创建一个名为react-frontend的目录。在该目录中,它将生成初始项目结构并安装传递依赖项:
react-frontend
├── README.md
├── node_modules
├── package.json
├── .gitignore
├── public
│ ├── favicon.ico
│ ├── index.html
│ ├── logo192.png
│ ├── logo512.png
│ ├── manifest.json
│ └── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── index.css
├── index.js
├── logo.svg
└── serviceWorker.js
让我们探索一下 react 项目的重要文件和文件夹。
对于要构建的项目,这些文件必须以准确的文件名存在:
- public/index.html 是页面模板;
- src/index.js 是 JavaScript 入口点。
您可以删除或重命名其他文件 让我们快速探索项目结构。
package.json - package.json 文件包含我们的 React JS 项目所需的所有依赖项。最重要的是,您可以检查您正在使用的 React 的当前版本。它具有启动、构建和弹出我们的 React 应用程序的所有脚本。
公共文件夹 - 公共文件夹包含 index.html。由于 react 用于构建单页应用程序,因此我们有一个 HTML 文件来呈现我们所有的组件。基本上,它是一个 HTML 模板。它有一个 以 id 为根的div 元素, 我们所有的组件都在这个 div 中呈现, index.html 作为完整反应应用程序的单个页面。
src 文件夹- 在这个文件夹中,我们有所有的全局 javascript 和 CSS 文件。我们将要构建的所有不同组件都坐在这里。
index.js - 这是你的 react 应用程序的顶级渲染器。
node_modules - NPM 或 Yarn 安装的所有包都将驻留在 node_modules 文件夹中。
App.js - App.js 文件包含我们的 App 组件的定义,该组件实际上在浏览器中呈现,这是根组件。
2 - 使用 NPM 在 React 中添加引导程序
打开一个新的终端窗口,导航到项目的文件夹,然后运行以下命令:
$ npm install bootstrap --save
安装 bootstrap 包后,你需要将它导入到你的 React 应用入口文件中。
打开 src/index.js 文件并添加以下代码:
import 'bootstrap/dist/css/bootstrap.min.css';
src/index.js
下面是 index.js 文件的完整代码:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import 'bootstrap/dist/css/bootstrap.min.css';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
3. React 服务组件 - REST API 调用
对于我们的 API 调用,我们将使用 Axios。下面是安装 Axios的 npm 命令。
npm add axios
下面是通过 Axios 进行 HTTP REST 调用的UserService.js服务实现。
我们的后端用户端点位于 http://localhost:8080/api/users。
import axios from 'axios'
const USERS_REST_API_URL = 'http://localhost:8080/api/users';
class UserService {
getUsers(){
return axios.get(USERS_REST_API_URL);
}
}
export default new UserService();
确保创建UserService类的对象,将其导出为:
export default new UserService();
4. 开发一个 React 组件
组件是我们整个 React 应用程序的构建块。它们就像函数一样,接受道具、状态方面的输入,并输出在浏览器中呈现的 UI。它们是可重复使用和可组合的。
React 组件可以是函数组件,也可以是类组件。在本例中,我们将使用类组件。
让我们创建一个UserComponent.js文件并向其中添加以下代码。
import React from 'react';
import UserService from '../services/UserService';
class UserComponent extends React.Component {
constructor(props){
super(props)
this.state = {
users:[]
}
}
componentDidMount(){
UserService.getUsers().then((response) => {
this.setState({ users: response.data})
});
}
render (){
return (
<div>
<h1 className = "text-center"> Users List</h1>
<table className = "table table-striped">
<thead>
<tr>
<td> User Id</td>
<td> User First Name</td>
<td> User Last Name</td>
<td> User Email Id</td>
</tr>
</thead>
<tbody>
{
this.state.users.map(
user =>
<tr key = {user.id}>
<td> {user.id}</td>
<td> {user.firstName}</td>
<td> {user.lastName}</td>
<td> {user.email}</td>
</tr>
)
}
</tbody>
</table>
</div>
)
}
}
export default UserComponent
让我们一步一步理解上面的代码。
-
constructor() -在安装组件之前调用构造函数 () 。在构造函数中,我们声明了状态变量并绑定了不同的方法,以便可以从 render() 方法内部的状态访问它们。
-
componentDidMount() -一旦组件安装并准备好,就会调用 componentDidMount() 。
-
render() - render()方法是最常用的生命周期方法。render()方法实际上将HTML 输出到 DOM。
我们正在使用map 操作符来遍历我们的用户列表并创建如下视图:
{
this.state.users.map(
user =>
<tr key = {user.id}>
<td> {user.id}</td>
<td> {user.firstName}</td>
<td> {user.lastName}</td>
<td> {user.email}</td>
</tr>
)
}
5. 应用.js
在上一步中,我们已经创建了UserComponent,所以让我们继续将UserComponent添加到 App组件中:
import React from 'react';
import logo from './logo.svg';
import './App.css';
import UserComponent from './components/UserComponent';
function App() {
return (
<div className="App">
<UserComponent />
</div>
);
}
export default App;
6. 运行反应应用
使用以下命令启动项目:
npm start
使用yarn启动项目:
yarn start
在开发模式下运行应用程序。打开 http://localhost:3000 在浏览器中查看。
结论
在本教程中,我们创建了一个简单的“单页应用程序”,使用 React 作为前端, spring boot 作为后端。我们还看到了如何使用 Axios HTTP 库将 React 前端应用程序与 Spring Boot 后端集成。
如果您想在 React App 中使用 React Hooks,请查看 React JS (React Hooks) + Spring Boot 教程