创建于:11-04-2020
上次更新:Jordy Coder的10-09-2021
贡献者:
Jeffrey Spaan(完整堆栈开发人员 @ codeBean)
Jordy Hamwijk(完整堆栈开发人员 @ codeBean)
欢迎开发人员。这是使用React和Spring Boot开发第一个Web应用程序的第一个教程。
向前迈进,我们将使用此存储库作为任何其他存储库的起点,我们将在Github上发布。
在本教程中,我们将介绍基础知识,并设置带有弹簧靴后端的React Frontend。
React是一个开源JavaScript库,用于构建专门用于单页应用程序的用户界面。
它用于处理Web和移动应用程序的视图层。 React还允许我们创建可重复使用的UI组件。
UI组件的使用可以减少开发并减少应用程序的开发时间。
Spring Boot是一种基于Java的框架,用于创建微型服务。
通过使用Spring Boot依赖项来简化应用程序的后端,这使您只需选择所需的依赖项即可快速设置应用程序的后端。
说到这,让我们从立即创建后端开始。
在您的浏览器中,打开:https://start.spring.io
Maven ProjectJava2.2.6nl.codebeanreact-spring-bootReact and Spring Boot TutorialJAR8Spring Web要创建预先生成的Spring Boot应用程序,请单击:生成
在您的硬驱动器上下载zip文件。打开zip文件并提取项目文件夹。
打开您喜欢的IDE中的项目文件夹。
项目对象模型或POM是Maven的基本工作单位。
它是一个XML文件,其中包含有关项目和配置详细信息用于构建项目的信息。
以下列表显示您选择一个Maven项目时创建的POM.xml文件:
<? 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.6.RELEASE</ version >
< relativePath /> <!-- lookup parent from repository -->
</ parent >
< groupId >nl.codebean</ groupId >
< artifactId >react-spring-boot</ artifactId >
< version >0.0.1-SNAPSHOT</ version >
< name >react-spring-boot</ name >
< description >React and Spring Boot Tutorial</ 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 >
</ dependencies >
< build >
< plugins >
< plugin >
< groupId >org.springframework.boot</ groupId >
< artifactId >spring-boot-maven-plugin</ artifactId >
</ plugin >
</ plugins >
</ build >
</ project >让我们添加一项服务以使应用程序输出一些数据。
为此,请添加一个名为: GreetController.java的控制器
将控制器保存在src/main/java/nl/codebean/reactspringboot/GreetController.java
package nl . codebean . reactspringboot ;
import org . springframework . web . bind . annotation . RequestMapping ;
import org . springframework . web . bind . annotation . RestController ;
@ RestController
public class GreetController {
@ RequestMapping ( "/api/greet" )
public String greet () {
return "Greetings from CodeBean!" ;
}
} @RestController :这是一个弹簧启动注释,将类标记为控制器;
@RequestMapping :这是一个弹簧靴注释,将"/api/greet"映射到greet()方法;从浏览器调用或通过在命令行上使用卷曲时,该方法仅返回文本。这是因为@RestController结合了@Controller和@ResponseBody ,这两个注释导致Web请求返回数据而不是视图。
现在,让我们在终端运行应用程序。
要启动该应用程序,请打开命令终端并执行以下任务(显示其输出):
在本教程中,终端命令在原始命令的前面标有>。
> mvn spring-boot:run
2020-04-12 10:42:20.303 INFO 2232 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2020-04-12 10:42:20.311 INFO 2232 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2020-04-12 10:42:20.312 INFO 2232 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.33]
2020-04-12 10:42:20.378 INFO 2232 --- [ main] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2020-04-12 10:42:20.378 INFO 2232 --- [ main] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 896 ms
2020-04-12 10:42:20.503 INFO 2232 --- [ main] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2020-04-12 10:42:20.610 INFO 2232 --- [ main] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-04-12 10:42:20.612 INFO 2232 --- [ main] n.c.r.ReactSpringBootApplication : Started ReactSpringBootApplication in 1.444 seconds (JVM running for 1.78)启动应用程序后,让我们(在单独的命令终端)运行服务。执行以下任务(以其输出显示):
> curl http://localhost:8080/api/greet
Greetings from CodeBean!伟大的工作! Spring Boot休息服务现在正在启动并运行。
让我们继续将后端数据传到前端。
现在,我们将使用称为React的JavaScript库构建前端。
在前端,我们能够获取后端生成的数据。让我们开始吧!
> npx create-react-app frontend
Creating a new React app in ../react-spring-boot/frontend
Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...
Installing template dependencies using npm...
Removing template package using npm...
Success! Created frontend at ../react-spring-boot/frontend
We suggest that you begin by typing:
cd frontend
npm start说明很清楚,让我们继续这样做(显示出其输出):
> cd frontend
> npm start
Compiled successfully!
You can now view frontend in the browser.
Local: http://localhost:3000
打开浏览器,然后访问http:// localhost:3000查看React应用程序。
它应该看起来像这样:
我们的下一个任务是从前端(客户端)中显示后端(服务器端)的API数据。
后端在端口8080 http://localhost:8080
前端在端口3000 http://localhost:3000
现在两个端口都在彼此并肩运行而没有任何互连。为了允许从前端端口到后端端口的读写访问,我们需要设置一个允许数据传输的代理。
通过将proxy字段添加到您的frontend/package.json文件来解决,该文件允许端口3000从/到端口8080传输数据。
"proxy" : " http://localhost:8080 " ,您的frontend/package.json文件现在应该看起来像这样:
{
"name" : " frontend " ,
"version" : " 0.1.0 " ,
"private" : true ,
"dependencies" : {
"@testing-library/jest-dom" : " ^4.2.4 " ,
"@testing-library/react" : " ^9.5.0 " ,
"@testing-library/user-event" : " ^7.2.1 " ,
"react" : " ^16.13.1 " ,
"react-dom" : " ^16.13.1 " ,
"react-scripts" : " 3.4.1 "
},
"scripts" : {
"start" : " react-scripts start " ,
"build" : " react-scripts build " ,
"test" : " react-scripts test " ,
"eject" : " react-scripts eject "
},
"proxy" : " http://localhost:8080 " ,
"eslintConfig" : {
"extends" : " react-app "
},
"browserslist" : {
"production" : [
" >0.2% " ,
" not dead " ,
" not op_mini all "
],
"development" : [
" last 1 chrome version " ,
" last 1 firefox version " ,
" last 1 safari version "
]
}
}要了解有关代理API请求的更多信息,请参见Create React应用程序的文档。
让我们测试我们现在是否也能够从前端访问数据。
首先,重新启动您的前端。要停止当前会话,请在IDE终端窗口中键入CTRL + C。
重新启动前端后,打开一个新的终端窗口和键入后面的命令(显示了其输出):
> curl http://localhost:3000/api/greet
Greetings from CodeBean!我们快到了。现在,我们将从后端获取数据以显示前端。
打开您的/frontend/src文件夹。添加一个名为components的文件夹。
在components文件夹中,添加一个名为Greet.js的文件
根据React最佳实践,组件文件夹将包含所有充当组件的文件。
根据React最佳实践,组件名称将以大写字母开头。
您的/src文件夹结构现在看起来像这样:
.
├─ ...
├─ components
│ └─ Greet.js
└─ ...
将以下代码添加到您的Greet.js文件中。
import React , { useState , useEffect } from 'react' ;
const Greet = ( ) => {
const [ greet , setGreet ] = useState ( "" ) ;
async function fetchData ( ) {
let res = await fetch ( '/api/greet' ) ;
let greet = await res . text ( )
setGreet ( greet ) ;
}
useEffect ( ( ) => {
fetchData ( ) ;
} , [ ] ) ;
return (
< div >
< h4 > { greet } </ h4 >
</ div >
)
}
export default Greet ;现在,打开位于/frontend/src文件夹中的App.js文件。
在这里,我们将通过import Greet from './components/Greet';来导入Greet.js组件';和<Greet />到App.js文件。
您的代码应该看起来像这样:
import React from 'react' ;
import logo from './logo.svg' ;
import './App.css' ;
import Greet from './components/Greet' ;
function App ( ) {
return (
< div className = "App" >
< header className = "App-header" >
< img src = { logo } className = "App-logo" alt = "logo" />
< p >
Edit < code > src/App.js </ code > and save to reload.
</ p >
< Greet />
< a
className = "App-link"
href = "https://reactjs.org"
target = "_blank"
rel = "noopener noreferrer"
>
Learn React
</ a >
</ header >
</ div >
) ;
}
export default App ;您的React前端现在应显示后端API的文本。
现在,您的React Frontend与您的Spring Boot后端连接,这使您的应用程序可以从/将数据从/将数据写入服务器。
希望您喜欢遵循本教程,不要忘记给这个存储库一个明星。
在GitHub上关注CodeBean University,并使用新的有趣教程进行更新。
在下一个教程中,我们将制作一个Spring Boot Restful API应用程序,我们将与PostgreSQL数据库连接。