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接收参数的几种常用方式盘点 ...
随机推荐
- vue-cli(vue脚手架)超详细教程
都说Vue2简单上手容易,的确,看了官方文档确实觉得上手很快,除了ES6语法和webpack的配置让你感到陌生,重要的是思路的变换,以前用jq随便拿全局变量和修改dom的锤子不能用了,vu ...
- datatables:如何禁用一列的排序
第一列是checkbox列,不需要排序,所以需要禁用掉. 代码如下: var table = $('#example1').DataTable( { 'paging' : true, 'lengthC ...
- hybrid programming based on python and C/C++
Python/C API Reference Manual¶ https://docs.python.org/3/c-api/index.html Extending and Embedding th ...
- ASP.NET MVC5高级编程 之 模型
1. 为MVC Music Store建模 Models文件夹(右击) --> 添加 --> 类 为类添加对应的属性: public class Album { public virtua ...
- Mysql 数据库安装与配置详解
目录 一.概述 二.MySQL安装 三.安装成功验证 四.NavicatforMySQL下载及使用 一.概述 MySQL版本:5.7.17 下载地址:http://rj.baidu.com/soft/ ...
- JMeter3.2生成图形化HTML报告
JMeter3.0引入了Dashboard Report,用于生成HTML页面格式图形化报告的扩展模块. 该模块支持通过两种方式生成多维度图形化测试报告: 在JMeter性能测试结束时,自动生成本次测 ...
- oracle 报表带小计合计
selectcase when (grouping(glbm)=1) then '合计' else DECODE(glbm,null,'',glbm) end glbm,case when (grou ...
- Python-Django-Ajax进阶
ajax上传文件: <h2>基于ajax上传文件</h2><p>名字 <input type="text" id="filena ...
- headless&unittest
为什么要使用 headless 测试? headless broswer 可以给测试带来显著好处: 对于 UI 自动化测试,少了真实浏览器加载 css,js 以及渲染页面的工作.无头测试要比真实浏览器 ...
- Confluence 6 其他 MBeans 和高 CPU 消耗线程
其他 MBeans 希望监控 Hibernate 和 Hazelcast(仅针对 Confluence 数据中心)你需要在你的 setenv.sh / setenv.bat 文件中添加下面的内容. s ...