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接收参数的几种常用方式盘点 ...
随机推荐
- centos7.4_x86_64安装grafana5.2.1并安装常用zabbix插件
获取并安装grafana5.2.1# wget https://s3-us-west-2.amazonaws.com/grafana-releases/release/grafana-5.2.1-1. ...
- Android来电拦截及来电转移
1. 电话拦截这个功能大家可能都知道了,就是利用反射原理调用ITelephony的隐藏方法来实现.这个就不说了,在附件的代码里有.2.拦截后提示忙音/空号/已关机/已停机这个功能其实是要用到MMI指令 ...
- Vue -- 数据监听
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【原创】大数据基础之Flume(2)Sink代码解析
flume sink核心类结构 1 核心接口Sink org.apache.flume.Sink /** * <p>Requests the sink to attempt to cons ...
- html跳转指定位置-利用锚点
比如我现在 a.html 的时候,我想跳转到 b.html ,并且是 b.html 的某一个位置,用 <a href=>, a.html里: <a href="b.html ...
- Android中播放音乐的几种方式
前言 前几天一直在研究RxJava2,也写了记录了几篇博客,但因为工作任务原因,需要研究音频相关的知识,暂时放下Rxjava,本文的demo中,MediaPalyer 部分使用RxJava编写一点逻辑 ...
- 微信小程序商业级实战
1.微信开放能力:微信支付.微信登录.二维码生成.分享
- Confluence 6 缓存性能示例
有关 Confluence 的缓存性能如何设置,让我们看看下面的表: 缓存(Caches) % 使用的缓存(Used) % 有效率(Effectiveness) 对象/大小(Objects/Size) ...
- Python yield使用浅析
yield可将一个函数变成生成器,每次调用时,返回yield的结果,下次迭代时,从yield 下条语句开始执行. 一个典型的例子,斐波拉切数列: def fab(max): n, a, b = 0, ...
- python魔法函数之__getattr__与__getattribute__
getattr 在访问对象的属性不存在时,调用__getattr__,如果没有定义该魔法函数会报错 class Test: def __init__(self, name, age): self.na ...