springboot(12)- 整合web开发(4)- @ControllerAdvice

    技术2025-05-01  35

    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; } }

    Processed: 0.015, SQL: 9