java解析json報文,springboot傳入json和文件_Spring Boot之 Controller 接收參數和返回數據總結(包括上傳、下載文件).

 2023-11-19 阅读 34 评论 0

摘要:server:port: 8088servlet:context-path: /sidspring:mvc:view:prefix: /suffix: .html/*** 返回界面 index.html* @Controller修飾的類 直接定義方法返回值為String* */@RequestMapping(value = "/index")public String index(){return "index";

server:

port: 8088

servlet:

context-path: /sid

spring:

mvc:

view:

prefix: /

suffix: .html

33458831dd87fc258417d391000b8903.png

/**

* 返回界面 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;

}

ae196c969b80f39be1b0045c71554fb9.png

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 list =new ArrayList();

list.add(t);

return list;

}

8f9510ad20c643e3e344f7a7bd7a0b07.png

3.返回時直接拋出自定義異常

/**

* 返回時直接拋出自定義異常

* */

@RequestMapping(value = "/list", method = RequestMethod.POST)

@ResponseBody

public List list(@RequestParam("name") String name , @RequestParam("age") String age){

TestModel t =getModel( name , age);

if(t != null){

throw new MyException("測試拋出自定義異常");

}

List list =new ArrayList();

list.add(t);

list.add(t);

return list;

}

1e71279d8f0d765cf758bf8f321e0c4a.png

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 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,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有返回值

}

}

c56470392f576a4bfdcc0d4b835909cf.png

e33a53a1086bafdb25af74fc234fa06c.png

--------------------------------------

75d2f93899bac8a4d2f524f60c8e9f35.png

5.返回自定義類,其中有code msg error data 而查詢結果在data中

MyResponse.java

package com.sid.springtboot.test.springboottest;

public class MyResponse {

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 list =new ArrayList();

list.add(t1);

list.add(t1);

list.add(t1);

return new MyResponse("1","success",null,list);

}catch (MyException e){

return new MyResponse<>("0",null,e.getMessage(),null);

}

}

d074653c821155d840c22999e63c3cbb.png

45d4909c252c6bd773bbfe89eecb727e.png

三、上傳、下載文件

上傳文件

@PostMapping("/upload")

@ResponseBody

public Map 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 result = new HashMap<>(16);

result.put("contentType", file.getContentType());

result.put("fileName", file.getOriginalFilename());

result.put("fileSize", file.getSize() + "");

return result;

}

a2a66476293540aaba397bb1a4fc2e63.png

下載文件

1.通過ResponseEntity實現

封裝ResponseEntity,將文件流寫入body中。這里注意一點,就是文件的格式需要根據具體文件的類型來設置,一般默認為application/octet-stream。文件頭中設置緩存,以及文件的名字。文件的名字寫入了,都可以避免出現文件隨機產生名字,而不能識別的問題。

---------------------

@GetMapping("/download")

public ResponseEntity 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;

}

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/3/182559.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息