SpringBoot前后端接收数据 的 注解

一、非JSON格式的数据


1.普通请求 ( 参数列表直接声明接收 )

前端请求: http://localhost:8080/user/001?username=jack&password=12345688
@RestController
@RequestMapping("/user")
public class UserController {
	//这里用RequestMapping() 是因为可以接收前端任意方式的请求,例:GET、POST...
    @RequestMapping("/001") 
    public String save(String username, String password){
        System.out.println("username:  "+username);
        System.out.println("password:  "+password);
        return "success";
    }
}	 //如果前端声明了很多请求参数这种会蛮烦,演变成了下面的用实体类接收

前端: 请求参数名 <<==>> 后端: 接收参数名 两者要保持一致


2.普通请求 ( 用实体类接收 )

前端请求: http://localhost:8080/user/002?username=jack&password=12345688
@RestController
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/002")
	public String save2(User user){
        System.out.println(user);
        return "success";
    }
    
}

后端: 接收类里的属性名 <<==>> 前端: 请求参数名字 两者要保持一致 (否则接收不到为null)


3.RestFul风格请求 @PathVariable

在这里插入图片描述


例如: ( 如果接收有异常,会报500错误 )

在这里插入图片描述


4.普通请求 ( 用HttpServletRequest对象 直接接受 )

前端请求:http://localhost:8080/user/004?username=jack&password=123456
@RestController
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/004")
    public String save4(HttpServletRequest request){
        //request对象中的数据是以 key-value键值对存储的
        //key就是前端的参数名称username=jack (key就是username)
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username:  "+username);
        System.out.println("password:  "+password);
        return "success";
    }
    
}



二、JSON格式的数据


1.直接使用实体类对象来接收 @RequestBody

前提: 前端提交数据时,数据类型要选择JSON格式的

前端请求:http://localhost:8080/user/005

请求的数据如下:
{
"username":"xiaoming",
"password":"888"
}
@RestController
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/005")
    public String save5(@RequestBody User user){
        System.out.println(user);
        return "success";
    }
    
}

如果前端JSON中的key后端实体类里的字段名 不一致,后端接收为null


2.使用Map集合来接收 @RequestBody

前端请求:http://localhost:8080/user/006

请求的数据如下:
{
"username":"xiaoming",
"password":"888"
}
@RestController
@RequestMapping("/user")
public class UserController {
	
	@RequestMapping("/006")
    public String save6(@RequestBody Map map){
        String username = (String) map.get("username");
        String password = (String) map.get("password");
        System.out.println("username:  "+username);
        System.out.println("password:  "+password);
        return "success";
    }
    
}

如果Map前不使用@RequestBody注解,后端map就拿不到值


三、小总结

只要前端传递的是JSON数据, 后端接收时必须使用 @RequestBody 注解

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值