前后端分离及springboot+react简单demo
1.前后端分离基本概念
前后端通过规定restful接口即前后端数据交互的格式,然后独自开发。假设某一个业务前后端所定义的json格式如下:
{//url: /user/info?id=xxx"id":xxxx,//int 类型"type":"xxx",//string 类型“attributes":[{"one":"xxx","two":"xxx"},]
}
那么后端只需要根据业务逻辑实现,最后将返回的数据格式以上述的json格式返回给前端即可。前端通过json获取对应数据并展示出来。从而实现前后端的并行开发,提升开发效率。
另外还有一种引入NodeJS层作为服务桥接层的前后端分离架构,在本文不做介绍。
2.前后端分离架构的好处
- 前后端未分离时,后端开发人员需要了解前端的相关技术并掌握JSP语言。前后端分离之后,后端开发人员可以专注于服务器端逻辑开发,提升服务器性能等。ps:当然后端学一些前端相关的html,Javascript也是挺有意义的。
- 前后端定义好接口之后,双方可以并行开发,提升研发效率。
3.springboot+react简单的demo
在此假设读者已掌握基础的springboot及react。另,读者还需了解跨域访问
后端实现
IDE:IDEA 2020.3
JDK:1.8
spring-boot-starter-web:2.3.7
此demo只有一个简单的Controller,如下:
@Controller
public class UserController {&#64;RequestMapping("/user/info")&#64;ResponseBody &#64;CrossOrigin public UserInfoResp UserInfo(&#64;RequestParam("id") int id){UserInfoResp resp&#61;new UserInfoResp();if(id!&#61;1){return null;}resp.id&#61;id;resp.name&#61;"hello";List<attribute> attributes&#61;new ArrayList<>();attribute attr1 &#61; new attribute();attr1.one&#61;"temp";attr1.two&#61;"test";attributes.add(attr1);resp.attributes&#61;attributes;return resp;}
}
UserInfoResp类及attribute类&#xff1a;
class UserInfoResp{int id;String name;List<attribute> attributes;
}class attribute{String one;String two;
}
前端实现
IDE:WebStorm2020.1
Node: v15.5.0
npx create-react-app projectname
创建一个react项目
修改src/App.js文件如下&#xff1a;
class App extends React.Component {
}
export default App;
在state中初始化userinfo
state&#61;{userinfo: {attributes:[]}}
重点&#xff1a;通过fetch获取后端数据
getInfo() {let myHeader&#61;new Headers({&#39;Access-Control-Allow-Origin&#39;: &#39;http://localhost:3000&#39;,})let url&#61;&#39;http://localhost:8080/user/info?id&#61;1&#39;fetch(url,{method:&#39;GET&#39;,headers:myHeader,mode:&#39;cors&#39;}).then(res&#61;>res.json()).then(data&#61;>{if(data &#61;&#61;&#61;null){window.alert("根据此id查询不到用户")return}this.setState({userinfo:data})})}componentWillMount() {this.getInfo()}
将从后端获取的userinfo展示&#xff1a;
render(){return (<div><span >id is {this.state.userinfo.id} </span><br/><span>name is {this.state.userinfo.name}</span><br/>{this.state.userinfo.attributes.map((attr,index)&#61;>{return(<div><span>第{index}个属性&#xff1a;</span><br/><span>one:{attr["one"]}</span><br/><span>two:{attr.two}</span></div>)})}</div>);}