SpringMVC 参数接收

Java Bean

1.当客户端发起http POST请求的时候,经常以JSON格式发送参数(Request Body中),这时候请求参数过多,可以以对象的方式传递参数,SpringMVC使用对应的java bean接收这样的参数.

重要:@Requestbody---POST请求的时候,接受前端所传json对象并绑定java bean。

有的时候直接没有用@requestbody这个注解,直接在入参的地方写了参数bean,也可以直接解析到,为什么?

答案:@RequestBody注解常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,比如说:application/json或者是application/xml等。一般情况下来说常用其来处理application/json类型。如果前端发送的数据的 content-type 就是默认的application/x-www-form-urlcoded编码,则不加@RequestBody,不然会报错儿。

{"userName":"admin",

"password": "admin",

"phone":"13678965789",

"email":"test@163.com"

}

SpringMVC这样接收参数:

    @PostMapping("adduser")
    public Object addNewUser(@RequestBody(required=false) User user) throws Exception {
        userService.add(user);
        return ResponseResult.success("Success");
    }

2.发送GET请求,并且参数很多的时候,也可以以java bean的方式接收参数。

http://localhost:8087/dd/user/table?ip=localhost&port=3306&dbName=multi_datasource_test2&username=root&password=123456

SpringMVC这样接收参数:这次没有加@Requestbody,因为@Requestbody是给POST请求用的

    @GetMapping("table")
    public Object findWithDbInfo(DbInfo dbInfo) throws Exception {
        /**
         * http://localhost:8080/dd/user/table? ip=localhost&port=3310&dbName=mytest&username=root&password=111111
         * **/
        //数据源key
        String newDsKey = System.currentTimeMillis()+"";
//        //添加数据源
//        DataSourceUtil.addDataSourceToDynamic(newDsKey,dbInfo);
//        DynamicDataSourceContextHolder.setContextKey(newDsKey);
//        //查询表信息
//        List<Map<String, Object>> tables = tableMapper.selectTableList();
//        DynamicDataSourceContextHolder.removeContextKey();

        //使用代理切换数据源
        TableMapper tableMapperProxy = (TableMapper)JdkParamDsMethodProxy.createProxyInstance(tableMapper, newDsKey, dbInfo);
        List<Map<String, Object>> tables = tableMapperProxy.selectTableList();
        return ResponseResult.success(tables);
    }

@RequestParam 和 @PathVariable 注解是我们在SpringMVC中最常用的接收http request参数的注解。

@RequestParam

客户端发起了这样的请求。

http://localhost:8080/springmvc/login/ldap?name=admin&password=admin

服务端springMVC应该这样接收参数。

public String getDetails(
    @RequestParam(value="name", required=true) String name,
    @RequestParam(value="password", required=false) String password){
...

@RequestParam 支持下面四种参数:

  • name 绑定本次参数的名称,要跟URL上面的一样
  • value 跟name一样的作用,是name属性的一个别名
  • required 这个参数是不是必须的
  • defaultValue 如果本次请求没有携带这个参数,或者参数为空,那么就会启用默认值

@PathVariable

RESTFULL逐渐成为影响Web框架、Web协议与Web应用设计的重要概念。SpringMVC很好的支持了RESTFULL.

@PathVariable 这个注解能够从url的path中获取参数

http://localhost:8080/springmvc/login/ldap?name=admin&password=admin

@PathVariable 与 @RequestParam可以混合使用,上面例子中的url在springMVC中这样写:

@RequestMapping("/login/{authtype}")
    public String getDetails(@PathVariable(value="authtype") String authtype,
    @RequestParam(value="name", required=true) String name,
    @RequestParam(value="password", required=false) String password){
.......
}

从url的path中获取到了参数authtype。

@RequestBody

@RequestBody对应的是POST请求的body,body即是获取的参数, 并且只有这一个参数。例如可以接收List<String>,Map<String, Object>, 对应的客户端可以发送数组["","",""],JSON格式数据。

一开始提到过的,@Requestbody---可以接受前端传json对象并绑定javabean

举例说明:

1.如果客户端发送POST请求, 数据为{"name": "bruce"},后端代码如下:

@RestController
public class UserController {
	// url请求拦截
	@RequestMapping("/userinfo")
	public void receive(@RequestBody(required=false) String name) {
		System.out.println("@RequestBody paramter: " + name);
	}
}

控制台将会打印出:

@RequestBody paramter : {"name":"bruce"}

而不是:

@RequestBody paramter : bruce

因为@RequestBody对应的是POST请求的body,body即是获取的参数

2.有的时候POST请求发送的JSON数据比较复杂,可以使用Map<String, Object>来接收参数。

JSON数据:

{

    "businessTypeID":"11",

    "indicators": [ {

        "indicatorName":"",

        "indicatorType":"",

        "status": ""

        },

        {

        "indicatorName":"",

        "indicatorType":"",

        "status": ""

        }]

}

    @Deprecated
    @RequestMapping(value = "/setTwoCascade", method = RequestMethod.POST)
    public Result<Long> setTwoCascade(@RequestBody(required=false) Map<String, Object> parameters) {
        Long businessTypeId = businessTypeService.setTwoCascade(parameters);
        return new Result<Long>(200, "successful", businessTypeId);
    }
	@Override
	public Long setTwoCascade(@RequestBody(required=false) Map<String, Object> parameters) {
		if (parameters.get("businessTypeID") == null || parameters.get("businessTypeID").equals("")) {
			return 0L;
		}
		Long businessTypeId =Long.valueOf((String) parameters.get("businessTypeID"));
		
		List<Map<String, Object>> indicatorlist = (List<Map<String, Object>>) parameters.get("indicators");
		if (indicatorlist == null) {
			return 0L;
		}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值