1 @ControllerAdvice
3 種用法
- 處理全局異常
- 預設全局數據
- 請求參數預處理
2 全局異常處理
- 依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
- 異常頁面
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>異常頁面</title>
</head>
<body>
<div th:text="${error}">
</div>
</body>
</html>
2.1 自定義異常類
package com.tzb.exception;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
@ControllerAdvice
public class MyException {
@ExceptionHandler(MaxUploadSizeExceededException.class)
public ModelAndView myCustomException(MaxUploadSizeExceededException e) throws IOException {
ModelAndView mv = new ModelAndView();
mv.addObject("error", "上傳文件大小超出限制");
mv.setViewName("myerror");
return mv;
}
/*@ExceptionHandler(MaxUploadSizeExceededException.class)
public void myCustomException(MaxUploadSizeExceededException e, HttpServletResponse resp) throws IOException {
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
out.write("上傳文件太大");
out.flush();
out.close();
}*/
}
2.2 主頁
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多文件上傳</title>
</head>
<body>
<form action="/upload" method="post" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
</body>
</html>
2.3 Controller
package com.tzb.controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.SimpleTimeZone;
import java.util.UUID;
@RestController
public class FileUploadController {
SimpleDateFormat sdf = new SimpleDateFormat("/yyyy/MM/dd/");
@PostMapping("/upload")
public String upload(MultipartFile file, HttpServletRequest req) {
String format = sdf.format(new Date());
String realPath = req.getServletContext().getRealPath("/img") + format;
File folder = new File(realPath);
if (!folder.exists()) {
folder.mkdirs();
}
String oldName = file.getOriginalFilename();
String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));
try {
file.transferTo(new File(folder, newName));
String url = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/img" + format + newName;
return url;
} catch (IOException e) {
e.printStackTrace();
}
return "error";
}
}
3 預設全局數據
在某個地方設置一個數據,這個數據在任意 Controller 都能訪問到。
package com.tzb;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalData {
@ModelAttribute(value = "info")
public Map<String,Object> mydata(){
Map<String, Object> map = new HashMap<>();
map.put("name", "Mike");
map.put("addr", "Beijing");
return map;
}
}
- Controller
@RestController
public class HelloController {
@GetMapping("/hello")
public String hello(Model model){
Map<String,Object> map = model.asMap();
Set<String> keySet = map.keySet();
for (String key : keySet) {
System.out.println(key + ": "+ map.get(key));
}
return "success";
}
}
4 請求參數預處理
-
實體類
-
Controller
@RestController
public class BookController {
@PostMapping("/book")
public void addBook(@ModelAttribute("b") Book book,@ModelAttribute("a") Author author){
System.out.println(book);
System.out.println(author);
}
}
- 全局數據配置
package com.tzb;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class GlobalData {
@InitBinder("a")
public void initA(WebDataBinder binder){
binder.setFieldDefaultPrefix("a.");
}
@InitBinder("b")
public void initB(WebDataBinder binder){
binder.setFieldDefaultPrefix("b.");
}
@ModelAttribute(value = "info")
public Map<String,Object> mydata(){
Map<String, Object> map = new HashMap<>();
map.put("name", "Mike");
map.put("addr", "Beijing");
return map;
}
}