/** * 測試接收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;
}
