SpringBoot之Controller接收参数和返回数据总结(包括上传、
下载⽂件)
⼀、接收参数(postman发送)
1.form表单
@RequestParam("name") String name
会把传递过来的Form表单中的name对应到formData⽅法的name参数上
该注解不能接收json传参
该注解表⽰name字段是必须⼊参的,否则会报错
@RequestParam(value = "name", required = false) String name
required = false表⽰必须⼊参
@RequestParam(value = "name", defaultValue = "admin") String name
defaultValue = "admin"表⽰当name⼊参为空的时候给它⼀个默认值admin
/**
* 测试接收form表单、URL的数据。不能接收Json数据
* */
@RequestMapping(value = "/test1", method = RequestMethod.POST)
public String formData(@RequestParam("name") String name , @RequestParam("age") int age){
String result = "receive name = "+name+" age = "+age;
System.out.println(result);
return result;
}
2.URL
代码跟1.form表单中的代码⼀样
3.动态接收URL中的数据
@PathVariable将URL中的占位符参数绑定到控制器处理⽅法的⼊参
此种情况下,url求情中⼀定要带占位符pageNo,pageSize的值,不然访问失败即访问时⼀定要⽤ localhost:8088/sid/test2/2/20
如果⽤ localhost:8088/sid/test2 则访问失败
/**
* 测试动态接收URL中的数据
* */
@RequestMapping(value = "/test2/{pageNo}/{pageSize}", method = RequestMethod.POST) public String urlData(@PathVariable int pageNo , @PathVariable int pageSize){
String result = "receive pageNo = "+pageNo+" pageSize = "+pageSize;
System.out.println(result);
return result;
}
4.json
@RequestBody 接收Json格式的数据需要加这个注解。该注解不能接收URL、Form表单传参/**
* 测试接收json数据
* */
@RequestMapping(value = "/jsonData", method = RequestMethod.POST)
public String jsonData(@RequestBody TestModel tm){
String result = "receive name = "+tm.getName()+" age = "+tm.getAge();
System.out.println(result);
return result;
}
5.@RequestMapping注解详细介绍
1.处理多个URL
@RestController
@RequestMapping("/home")
public class IndexController {
@RequestMapping(value = {
"",
"/page",
"page*",
"view/*,**/msg"
})
String indexMultipleMapping() {
return "Hello from index multiple mapping.";
}
}
这些 URL 都会由 indexMultipleMapping() 来处理:localhost:8080/home
localhost:8080/home/
localhost:8080/home/page
localhost:8080/home/pageabc
localhost:8080/home/view/
localhost:8080/home/view/view
2.HTTP的各种⽅法
如POST⽅法
@RequestMapping(value = "/test1", method = RequestMethod.POST)
3.produces、consumes
produces 指定返回的内容类型,仅当request请求头header中的(Accept)类型中包含该指定类型才返回。结合@ResponseBody使⽤---------------------
@Controller
@RequestMapping(value = "/t")
public class TestController {
//⽅法仅处理request请求中Accept头中包含了"text/html"的请求
@ResponseBody
@RequestMapping(value = "/produces",produces = {"text/html"})
public String testProduces(String name)
springboot和过滤器
{
return "test requestMapping produces attribute! "+name;
}
}
⽅法仅处理request请求中Accept头中包含了"text/html"的请求
⽐如⽤postman构建⼀个Accept=“application/json”的请求,请求会失败
comsumes  指定处理请求的提交内容类型(Content-Type),例如application/json, text/html。结合@RequestBody使⽤

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。