各种传参形式

一、QueryString

前端请求:http://localhost:8080/test/user/find?id=26&name=zhangsan

后端接收:

1.参数接收:

@RequestMapping("/find")
public void find(String id,String name){
 ...
}


2.对象接收:

@RequestMapping("/find")
public void find(User user){
 ...
}

自定义对象:

@Data
public class User{
  private String id;
  private String name;
}

二、路径传参

前端请求:http://localhost:8080/test/user/find/26/zhangsan

后端接收:

@RequestMapping("/find/{id}/{name}")
public void find(@PathVariable("id")String id,@PathVariable("name")String name){
 ...
}

三、form表单传递参数

前端form表单提交字符串请求:

<form action="http://localhost:8080/test/user/find">

	username:<input type="text" name="id" /><br>
	
	password:<input type="text" name="name" /> <br>
	
	<input type="submit" value=">

</form>

后端接收:

1.参数接收

@RequestMapping("/find")
public void find(String id,String name){
 ...
}

2.对象接收:

@RequestMapping("/find")
public void find(User user){
 ...
}


2、form表单提交文件请求:

<form action="http://localhost:8080/test/user/find" method= "post" enctype = "multipart/form-data">

    头像:<input type="file" name="photo" /><br>
    
    <input type="submit" value=">

</form>


接口:

@RequestMapping("/find",method = RequestMethod.POST)
public void find(MultipartFile photo){
 ...
}

四、ajax传递json字符串

ajax传递json字符串:

$.ajax({
        // 请求方式
        type:"post",
        // contentType 
        contentType:"application/json",
        // dataType
        dataType:"json",
        // url
        url:"http://localhost:8080/test/user/find",
        // 把JS的对象或数组序列化一个json 字符串
        data:{'id':1,'name':张三,'age':26,...},
        // result 为请求的返回结果对象
        success:function (result) {
            if (200 == result.code){
                alert("成功");
            }else{
                alert("失败");
            }
        }
    });


接口:

@RequestMapping("/find",method = RequestMethod.POST)
public void find(@RequestBody User user){
 ...
}

@Data
public class User{
  private int id;
  private String name;
  private int age;
}

@RequestBody:将请求中json字符串自动转化为java中的对象。

@ResponseBody: 将控制器方法返回值转为json格式字符串,并相应请求。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值