@ResponseBody和@RequestBody 的作用


简单说说@ResponseBody和@RequestBody 的作用

在SpringBoot项目中涉及到前后端交互必少不了的两个注解是@ResponseBody和@RequestBody,这两个注解的作用是相对应的。@ResponseBody 的作用是将后端处理后的数据以Json的形式返回给前台页面,@RequestBody 的作用是将前台的Json数据封装成对象的形式返回给后端,后端通过@RequestBody 在Controller的参数中接收。简单来说 @ResponseBody 是将数据从后端返给前端,@RequestBody 是将数据从前端返回给后端。

代码展示

前端表单页面

测试@RequestBody获取数据
用户名:
邮箱:

我在最开始的后端Controller页面。 (错误展示)

package com.atguigu.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author :LayTao
 * @date :Created in 2021/1/23 10:59
 * @description:测试获取前台传过来的参数、
 * @modified By:
 * @email: : laytao_mailstudy@163.com
 */
@Controller
public class ParameterTestController {

    @PostMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map map = new HashMap<>();
        map.put("content",content);
        return map;
    }
}

页面展示效果:

这样写的问题在于,我最开始使用的@Controller注解,发现虽然后端获取到了前台传递的参数,但是没有返回给前台,仔细一看,我是用的是@Controller,并没有@ResponseBody,于是加上@ResponseBody即可显示。
但是,还有个minor question 邮箱显示问题,也没注意,于是加上字符转义,正确Controller 代码如下:

package com.atguigu.boot.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.Map;

/**
 * @author :LayTao
 * @date :Created in 2021/1/23 10:59
 * @description:测试获取前台传过来的参数、
 * @modified By:
 * @email: : laytao_mailstudy@163.com
 */
//@ResponseBody
//@Controller
//@Controller 和 @ResponseBody可以合并成一个@RestController
@RestController
public class ParameterTestController {

    @PostMapping("/save")
    public Map postMethod(@RequestBody String content){
        Map map = new HashMap<>();
        try{
            //字符转义
            content= URLDecoder.decode(content,"utf-8");
            map.put("content",content);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        }
        
        System.out.println(map);
        return map;
    }
}

显示效果如下: