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 list =new ArrayList();
list.add(t);
return list;
}
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;
}
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有返回值
}
}
--------------------------------------
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);
}
}
三、上傳、下載文件
上傳文件
@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;
}
下載文件
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;
}
版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。
工作时间:8:00-18:00
客服电话
电子邮件
admin@qq.com
扫码二维码
获取最新动态