您的位置:首页 > 编程语言 > Java开发

SpringMVC Controller 的使用及请求参数的获取

2018-03-17 11:56 555 查看
PathVariable
顾名思义,获取路径中的参数;如请求为:http://localhost:8080/girl/23/hello/
后台相应的代码为:23即为后台获取的参数
PathVariable
@GetMapping(value = "/{id}/hello")
@ResponseBody
public int say(@PathVariable("id") Integer id){
return id;
}

RequestParam对于比较大众的请求;如:http://localhost:8080/girl/hello?id=23    则后台对应 的后台代码为(对于用不用加上RequestParam,若果想要使用其中比如设置默认值,则加上;无需求,可不加;同时,如果不加RequestParam,前后台参数应当名称一致;若使用RequestParam,可另取形参名,但RequestParam(),括号中的参数需与前台一致

):
@GetMapping(value = "/hello")
@ResponseBody
public int say(@RequestParam("id") Integer id){
return id;
}

@GetMapping(value = "/hello")
@ResponseBody
public int say(Integer id){
return id;
}

对于后台接收为多参数(主要拿实体层接),如:http://localhost:8080/girl/hi?age=56&name=张三      后台对应的代码为:@GetMapping(value = "/hi")
@ResponseBody
public String say(Person person ){
return person.getName();
}
对于前台传参为json数据,可以使用RequestBody,去接收参数(特别适用于ajax 通过json传值  ajax contentType设置为:
contentType: "application/json




后台代码为;@PostMapping(value = "/nice")
@ResponseBody
public String want(@RequestBody Person person ){
return person.getName();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  springmvc controller param