热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

前后端分离及springboot+react简单demo

前后端分离及springbootreact简单demo1.前后端分离基本概念前后端通过规定restful接口即前后端数据交互的格式,然后独自开发。假设某一个业务前
前后端分离及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 //如果返回值是字符串&#xff0c;那么直接将字符串写到客户端&#xff1b;如果是一个对象&#xff0c;会将对象转化为json串。&#64;CrossOrigin //允许跨域访问public UserInfoResp UserInfo(&#64;RequestParam("id") int id){UserInfoResp resp&#61;new UserInfoResp();if(id!&#61;1){return null;}// mock dataresp.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;//注意这些成员要有setter 和 getter&#xff0c;否则无法将对象转为json格式
}class attribute{String one;String two;//注意这些成员要有setter 和 getter&#xff0c;否则无法将对象转为json格式
}

前端实现

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/>{//userinfo中的attributes初始化为空list&#xff0c;否则会报undefined错误.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>);}


推荐阅读
author-avatar
郑青青11_875
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有