Spring Boot之 Controller 接收参数和返回数据总结(包括上传、下载文件)
/** * 测试接收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表单中的代码一样
/** * 测试动态接收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."; } }
---------------------
@Controller
@RequestMapping(value = "/t")
public class TestController { //方法仅处理request请求中Accept头中包含了"text/html"的请求
@ResponseBody
@RequestMapping(value = "/produces",produces = {"text/html"})
public String testProduces(String name)
{
return "test requestMapping produces attribute! "+name;
}
}
方法仅处理request请求中Accept头中包含了"text/html"的请求
比如用postman构建一个Accept=“application/json”的请求,请求会失败
comsumes 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html。结合@RequestBody使用
@Controller
@RequestMapping(value = "/t")
public class TestController { //方法仅处理request Content-Type为"application/json"类型的请求
@ResponseBody
@RequestMapping(value = "/consumes",consumes = {"application/json"})
public String testConsumes(@RequestBody String name)
{
return "test requestMapping consumes attribute! "+name;
}
}
方法仅处理request Content-Type为"application/json"类型的请求。
如果用postman构建一个Content-Type=“application/x-www-form-urlencoded”的请求,该方法不处理
4.headers
根据请求中的消息头内容缩小请求映射的范围
例如:
只处理header中testHeader = sid的请求
//方法仅处理header中testHeader = sid的请求
@ResponseBody
@RequestMapping(value = "/header",headers = {"testHeader = sid"})
public String testHeader(String name)
{
return "test requestMapping headers attribute! "+name;
}
构建一个header钟不带testHeader=sid的请求,会失败
必须要header中带testHeader=sid的请求的请求才处理
5.结合params属性处理请求参数
例如:
请求参数name=sid的时候由getParams方法处理
请求参数name=lee的时候由getParamsDifferent方法处理
@Controller
@RequestMapping(value = "/t")
public class TestController { @RequestMapping(value = "/params", params = {
"name=sid"
})
@ResponseBody
public String getParams(@RequestParam("name") String name) {
return "getParams method do " + name;
}
@RequestMapping(value = "/params", params = {
"name=lee"
})
@ResponseBody
public String getParamsDifferent(@RequestParam("name") String name) {
return "getParamsDifferent method do " + name;
}
}
@RestController注解,相当于@Controller+@ResponseBody两个注解的结合,返回json数据不需要在方法前面加@ResponseBody注解了,但使用@RestController这个注解,就不能返回jsp,html页面,视图解析器无法解析jsp,html页面
application.yml
---------------------
server:
port: 8088
servlet:
context-path: /sid spring:
mvc:
view:
prefix: /
suffix: .html
/**
* 返回界面 index.html
* @Controller修饰的类 直接定义方法返回值为String
* */
@RequestMapping(value = "/index")
public String index(){ return "index";
} /**返回界面 index.html
* @RestController修饰的类
* 需要配合视图解析器
* */
@RequestMapping("/indexmv")
public ModelAndView indexmv() {
ModelAndView mv = new ModelAndView("index");
return mv;
}
2.通过object返回查询结果
@ResponseBody会把返回值变成json
/**
* 直接查询得到的model类,@ResponseBody会把返回值变成json
* */
@RequestMapping(value = "/object", method = RequestMethod.POST)
@ResponseBody
public Object object(@RequestParam("name") String name , @RequestParam("age") String age){ TestModel t =getModel( name , age);
List<TestModel> list =new ArrayList();
list.add(t);
return list;
}
3.返回时直接抛出自定义异常
/**
* 返回时直接抛出自定义异常
* */
@RequestMapping(value = "/list", method = RequestMethod.POST)
@ResponseBody
public List<TestModel> list(@RequestParam("name") String name , @RequestParam("age") String age){
TestModel t =getModel( name , age); if(t != null){
throw new MyException("测试抛出自定义异常");
}
List<TestModel> list =new ArrayList();
list.add(t);
list.add(t);
return list;
}
4.返回ResponseEntity
两种不同的创建ResponseEntity的方式
/**
* 返回ResponseEntity
*
* ResponseEntity的优先级高于@ResponseBody。
* 在不是ResponseEntity的情况下才去检查有没有@ResponseBody注解。
* 如果响应类型是ResponseEntity可以不写@ResponseBody注解
* */
@RequestMapping(value = "/responseEntity", method = RequestMethod.POST)
public ResponseEntity<?> responseEntity(@RequestParam("name") String name , @RequestParam("age") String age){ try{
TestModel t =getModel( name , age);
if(!t.getAge().equals("27")){
throw new MyException("年龄错误!");
}
List<TestModel> list =new ArrayList();
list.add(t);
list.add(t);
HttpHeaders headers = new HttpHeaders();
//headers.set("Content-type", "application/json;charset=UTF-8");
headers.add("code", "1");
headers.add("msg", "success");
headers.add("error", "");
return new ResponseEntity<List>(list,headers,HttpStatus.OK);
}catch (MyException e){
return ResponseEntity.badRequest()
//.header("Content-type", "application/json;charset=UTF-8")
.header("code", "0")
.header("msg", "")
.header("error", e.getMessage())//中文乱码
.build();//build无返回值 body有返回值
}
}
--------------------------------------
5.返回自定义类,其中有code msg error data 而查询结果在data中
MyResponse.java
package com.sid.springtboot.test.springboottest; public class MyResponse<T> {
private String code;
private String msg;
private String error;
private T data; public MyResponse(String code, String msg, String error, T data) {
this.code = code;
this.msg = msg;
this.error = error;
this.data = data;
} public String getCode() {
return code;
} public void setCode(String code) {
this.code = code;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
} public String getError() {
return error;
} public void setError(String error) {
this.error = error;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
}
}
MyException.java
package com.sid.springtboot.test.springboottest; public class MyException extends RuntimeException{ private String errorCode;
private String msg; public MyException(String message) {
super(message);
} public MyException(String errorCode, String msg) {
this.errorCode = errorCode;
this.msg = msg;
} public String getErrorCode() {
return errorCode;
} public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
} public String getMsg() {
return msg;
} public void setMsg(String msg) {
this.msg = msg;
}
}
controller
/**
* 返回自定义类,其中有code msg error data 而查询结果在data中
* */
@RequestMapping(value = "/myResponse", method = RequestMethod.POST)
@ResponseBody
public MyResponse<?> myResponse(@RequestParam("name") String name , @RequestParam("age") String age){
try{
TestModel t1 =getModel( name , age);
if(!t1.getAge().equals("27")){
throw new MyException("年龄错误!");
}
List<TestModel> list =new ArrayList();
list.add(t1);
list.add(t1);
list.add(t1);
return new MyResponse<List>("1","success",null,list);
}catch (MyException e){
return new MyResponse<>("0",null,e.getMessage(),null);
}
}
三、上传、下载文件
上传文件
@PostMapping("/upload")
@ResponseBody
public Map<String, String> upload1(@RequestParam("file") MultipartFile file) throws IOException {
System.out.println("[文件类型] - [{}]"+ file.getContentType());
System.out.println("[文件名称] - [{}]"+ file.getOriginalFilename());
System.out.println("[文件大小] - [{}]"+ file.getSize());
//保存
file.transferTo(new File("D:\\gitrep\\springboot\\testFile\\" + file.getOriginalFilename()));
Map<String, String> result = new HashMap<>(16);
result.put("contentType", file.getContentType());
result.put("fileName", file.getOriginalFilename());
result.put("fileSize", file.getSize() + "");
return result;
}
下载文件
1.通过ResponseEntity<InputStreamResource>实现
---------------------
@GetMapping("/download")
public ResponseEntity<InputStreamResource> downloadFile() throws IOException {
String filePath = "D:\\gitrep\\springboot\\testFile\\" + "api-ms-win-core-console-l1-1-0.dll";
FileSystemResource file = new FileSystemResource(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
headers.add("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getFilename()));
headers.add("Pragma", "no-cache");
headers.add("Expires", "0"); return ResponseEntity.ok().headers(headers)
.contentLength(file.contentLength())
.contentType(MediaType.parseMediaType("application/octet-stream"))
.body(new InputStreamResource(file.getInputStream()));
}
2.用HttpServletResponse
@GetMapping("/download2")
public String downloadFile2( HttpServletResponse response) throws IOException {
// 获取指定目录下的文件
String fileName = "D:\\gitrep\\springboot\\testFile\\" + "api-ms-win-core-console-l1-1-0.dll";
File file = new File(fileName);
// 如果文件名存在,则进行下载
if (file.exists()) {
// 配置文件下载
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
// 下载文件能正常显示中文
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8")); // 实现文件下载
byte[] buffer = new byte[1024];
FileInputStream fis = null;
BufferedInputStream bis = null;
try {
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
OutputStream os = response.getOutputStream();
int i = bis.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = bis.read(buffer);
}
System.out.println("Download the song successfully!");
}
catch (Exception e) {
System.out.println("Download the song failed!");
} finally {
if (bis != null) {
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return null;
}
Spring Boot之 Controller 接收参数和返回数据总结(包括上传、下载文件)的更多相关文章
- 探究Spring Boot中的接收参数问题与客户端发送请求传递数据
结合此篇参考Spring框架学习笔记(9)--API接口设计相关知识及具体编码实现 在使用Spring Boot进行接收参数的时候,发现了许多问题,之前一直都很忙,最近才稍微有空研究一下此问题. 网上 ...
- Android+Spring Boot 选择+上传+下载文件
2021.02.03更新 1 概述 前端Android,上传与下载文件,使用OkHttp处理请求,后端使用Spring Boot,处理Android发送来的上传与下载请求.这个其实不难,就是特别多奇奇 ...
- Spring学习---Spring中利用组件实现从FTP服务器上传/下载文件
FtpUtil.java import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundExcepti ...
- spring mvc上传下载文件
前端jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEnc ...
- Spring Boot 之:接口参数校验
Spring Boot 之:接口参数校验,学习资料 网址 SpringBoot(八) JSR-303 数据验证(写的比较好) https://qq343509740.gitee.io/2018/07/ ...
- spring-boot-route(一)Controller接收参数的几种方式
Controller接收参数的常用方式总体可以分为三类.第一类是Get请求通过拼接url进行传递,第二类是Post请求通过请求体进行传递,第三类是通过请求头部进行参数传递. 1 @PathVariab ...
- Spring Boot获取前端页面参数的几种方式总结
Spring Boot的一个好处就是通过注解可以轻松获取前端页面的参数,之后可以将参数经过一系列处理传送到后台数据库. 获得的方式有很多种,这里稍微总结一下,大致分为以下几种: 1.指定前端url请求 ...
- 【转】spring boot application.properties 配置参数详情
multipart multipart.enabled 开启上传支持(默认:true) multipart.file-size-threshold: 大于该值的文件会被写到磁盘上 multipart. ...
- SpringBoot Controller接收参数的几种方式盘点
本文不再更新,可能存在内容过时的情况,实时更新请移步我的新博客:SpringBoot Controller接收参数的几种方式盘点: SpringBoot Controller接收参数的几种常用方式盘点 ...
随机推荐
- sqlserver记录去重
,[emp_name] ,[gender] ,[department] ,[salary] from [employee] select * from ( select ROW_NUMBER() ov ...
- ID过滤靓号写法(PHP和Nodejs版本)
1 前言 例如某APP的用户ID,需要按照一定规则把靓号先存取来,然后慢慢按要求释放靓号 2 代码 PHP版本如下: function genUserId(){ $id = ""; ...
- su命令
作用: 切换 用户 选项: -:可以更改当前目录为切换用户的家目录 使用: # 切换用户,当前所在用户目录不变 su 用户名 # 切换用户,当前所在目录改为切换对象的家目录 /home/用户名 su ...
- 关于如何实现Android透明状态栏的总结
开门见山. 原来做的效果,如下图(顶部有一条明显的橙色状态栏): a1.gif 改过之后(顶部状态栏是透明的): p2.gif 我发现网上写的一些文章,不够简洁明了,我整理了一下,复制粘贴一下 ...
- Android录制音频的三种方式
对于录制音频,Android系统就都自带了一个小小的应用,可是使用起来可能不是特别的灵活.所以有提供了另外的俩种. 下边来介绍下这三种录制的方式; 1.通过Intent调用系统的录音器功能,然后在录制 ...
- hive学习02-累加
求出当月的访问次数,截至当月前的每个月最大访问次数.截至当月前每个用户总的访问次数. 数据表如下 A,-, A,-, B,-, A,-, B,-, A,-, A,-, A,-, B,-, B,-, A ...
- table中border-collapse的问题
在table中,如果设置了border-collapse: collapse;,边框会合并,这时你修改top或bottom的颜色,会有问题 解决办法是:border-collapse: separat ...
- Confluence 6 数据库字符集编码和问题
数据库字符集编码 你的数据库和 JDBC 数据源连接必须配置为使用 UTF-8 编码(或者根据你配置的数据库来制定正确的 UTF-8 编码字符集,例如在 Oracle 中使用的是 AL32UTF8 ) ...
- Confluence 6 用户宏示例 - Hello World
下面示例显示了如何创建一个用户宏,在这个用户宏中显示文本 'Hello World!' 和任何用户在宏内容中输入的内容. Macro name helloworld Visibility Visibl ...
- centos之mysql安装配置使用
安装: 这里只安装得时mysql5.1,如果想安装5.6,看这里http://www.cnblogs.com/xuange306/p/8243859.html yum install -y mysq ...