Springboot后端接口开发

1、技术概述

现在大多数Web项目都采取前后端分离的方法,用Springboot后端获取前端传递的数据并进行业务逻辑处理和接口封装,是一项既简单又重要的操作。

2、技术详述

(1)确定传输方式

用POST提交不同传输方式获取参数的方式不同。

前端Content-Type JSON对象/字符串 后端参数获取方法
application/x-www-form-urlencoded 对象 @RequestParam 或者Servlet
application/json 字符串 @RequestBody

(2)定义规范的数据结构

建议最好自行定义一个规范的数据交互结构,既美观又实用

public class JsonUtil {
	public static HashMap<String, Object> success(Map<String, Object> data) {
		HashMap<String, Object> res = new HashMap<>();
		res.put("code", ResCode.SUCCESS.getCode());     //正确码
		res.put("msg", "");                             //备注消息
		res.put("data", data);                          //数据
		return res;
	}

效果如下:

{
    code: 200, //响应代码
    msg: '', //消息,正常时不带此条,出错时附加错误信息
    data: {} //数据
}

(3)GET请求

get请求一般用于查询数据,采用明文进行传输,一般用来获取一些无关用户信息的数据
请求方式一般通过url传参,如http://localhost:8080/hello
@GetMapping 组合注解,是 @RequestMapping(method = RequestMethod.GET) 的缩写
一个简单的例子:

@RestController
public class HelloController {
	@RequestMapping("/hello")
	public String hello() {
		return "Hello Spring Boot!";
	}
}

结果如下:

也可以在url后面带上参数,如http://localhost:8080/config?id=1,可以使用@RequestParam注解获取指定参数值。
代码如下:

@RestController
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ImageTypeService imageTypeService;
    @Autowired
    private CollectionService collectionService;

    @RequestMapping(value = "/config",produces = "application/json;charset=utf-8",method= RequestMethod.GET)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> getConfig(@RequestParam("id") Integer id){
        User user = userService.getUserById(id);
        List<String> imageTypeList = imageTypeService.getNameByUId(id);
        List<String> collectionList = collectionService.getNameByUId(id);
        Map<String,Object> map = new HashMap<String, Object>();
        map.put("name",user.getName());
        map.put("imageType",imageTypeList);
        map.put("collection",collectionList);
        return ResponseEntity.ok(JsonUtil.success(map));
    }
}

结果如下:

(4)POST请求

post请求一般用于修改数据,将前端的数据传送给后端,并返回指定内容。
当Ajax以application/x-www-form-urlencoded格式上传即使用JSON对象,后台只能使用@RequestParam 或者Servlet获取参数。 当Ajax以application/json格式上传即使用JSON字符串,后台可以使用@RequestBody或者@RequestParam获取。
@PostMapping 组合注解,是 @RequestMapping(method = RequestMethod.POST) 的缩写
后端代码如下:

public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private ImageTypeService imageTypeService;
    @Autowired
    private CollectionService collectionService;

    @RequestMapping(value = "/config",produces = "application/json;charset=utf-8",method= RequestMethod.POST)
    @ResponseBody
    public ResponseEntity<Map<String, Object>> postConfig(@RequestBody Map<String,Object> map){
        User user = new User();
        int id = (int)map.get("id");
        user.setId(id);
        user.setAmonutPerDay((int)map.get("amonutPerDay"));
        user.setBookId((int)map.get("bookId"));
        user.setTimesToChangeBackground((int)map.get("timesToChangeBackground"));
        user.setDurationKeepAfterRecite((int)map.get("durationKeepAfterRecite"));
        user.setTipsDuration((int)map.get("tipsDuration"));
        List<String> imageTypeList = (List<String>)map.get("imageList");
        List<String> collectionList = (List<String>)map.get("collection");
        userService.update(user);
        imageTypeService.update(imageTypeList,id);
        collectionService.update(collectionList,id);
        return ResponseEntity.ok(JsonUtil.success());
    }
}

前端代码:

function a(){
        $.ajax({
            url:"/config",
            type:"post",
            contentType: "application/json;charset=utf-8",
            data:JSON.stringify({
                "id":1,
                "amountPerDay":100,
                "bookId":1,
                "timesToChangeBackground": 1,
                "durationKeepAfterRecite": 1500,
                "tipsDuration": 1000,
                "imagesType": ['aa','abc','ade','cc'],
                "collection": ['admin', 'apple']
            })
        })
    }

结果展示:

3、技术使用中遇到的问题和解决过程

  1. 从前台传输的数据为空
    解决:@RequestBody或@RequestParam使用有误,首先要注意传输方式,其次要注意两者的用法及读取数据的格式有区别。
  2. @RequestBody与@ResponseBody的区别
    解决:@RequestBody的作用是将前端传来的json格式的数据转为自己定义好的javabean对象,不能写在方法名上方。@ResponseBody的作用是将后端以return返回的javabean类型数据转为json类型数据。

4、总结

后端接口开发算是一个最基本最简单的技术,但是它的意义非同一般,是Web项目能够实现前后端分离的关键技术。想要成为一名优秀的后端工程师,还需要更加努力学习。

5、参考文献、参考博客

CSDN博客:SpringBoot实现前后端数据交互、json数据交互、Controller接收参数的几种常用方式
CSDN博客:Spring中的注解@RequestBody和@ResponseBody的使用和区别

posted @ 2020-06-24 09:43  Dreamer2020  阅读(9693)  评论(0编辑  收藏  举报