File upload and exception handling for Spring Boot development
1 file upload
1 Front-end form
<form method="post" action="/upload" enctype="multipart/form-data">
<input type="file" name="file"><br>
<input type="submit" value="提交">
</form>
2 background receiving
/**
* MultipartFile 自动封装上传过来的文件
* @param email
* @param username
* @param headerImg
* @param photos
* @return
*/
@PostMapping("/upload")
public String upload(@RequestParam("email") String email,
@RequestParam("username") String username,
@RequestPart("headerImg") MultipartFile headerImg,
@RequestPart("photos") MultipartFile[] photos) throws IOException {
log.info("上传的信息:email={},username={},headerImg={},photos={}",
email,username,headerImg.getSize(),photos.length);
if(!headerImg.isEmpty()){
// 保存到文件服务器,OSS服务器
String originalFilename = headerImg.getOriginalFilename();
headerImg.transferTo(new File("D:\\cache\\"+originalFilename));
}
if(photos.length > 0){
for (MultipartFile photo : photos) {
if(!photo.isEmpty()){
String originalFilename = photo.getOriginalFilename();
photo.transferTo(new File("D:\\cache\\"+originalFilename));
}
}
}
return "main";
}
3 Configuration principles
**File upload automatic configuration class-MultipartAutoConfiguration-**MultipartProperties
-
Automatically configured StandardServletMultipartResolver [file upload parser]
-
1 Request comes in. Use the file upload parser to judge ( isMultipart ) and encapsulate ( resolveMultipart, return MultipartHttpServletRequest ) file upload request
-
2 parameter parser to parse the file content in the request and encapsulate it into MultipartFile
-
3 Encapsulate the file information in the request into a Map
-
2 exception handling
1 Error handling
1 default rule
By default, Spring Boot provides /error
a mapping that handles all errors
For machine clients, it will generate a JSON response with details of the error, HTTP status and exception message. For browser clients, respond with a "whitelabel" error view, rendering the same data in HTML
To customize it, add View
the parser aserror
- To completely replace the default behavior, you can implement
ErrorController
and register a bean definition of the type, or addErrorAttributes类型的组件
to use the existing mechanism but replace its contents - 4xx and 5xx pages under error/ will be automatically parsed
2 Custom error handling logic
Custom error pages:
- error/404.html error/5xx.html; if there is an accurate error status code, the page will match accurately, if not, then find 4xx.html; if there is no page, it will trigger a white page
@ControllerAdvice+@ExceptionHandler handles global exceptions; the bottom layer is supported by ExceptionHandlerExceptionResolver
@ResponseStatus+ custom exception; the bottom layer is ResponseStatusExceptionResolver, and the bottom layer calls response.sendError(statusCode, resolvedReason) for the information annotated by responsestatus; /error sent by tomcat
Spring underlying exceptions, such as parameter type conversion exceptions
- DefaultHandlerExceptionResolver handles exceptions at the bottom of the framework
Custom implementation of HandlerExceptionResolver to handle exceptions; it can be used as the default global exception handling rules
ErrorViewResolver implements custom exception handling
- response. sendError . The error request will be transferred to the controller
- Exceptions are not handled by anyone. tomcat underlying response.sendError. The error request will be transferred to the controller
- The page address that basicErrorController is going to is ErrorViewResolver
2 Principle of exception handling automatic configuration
ErrorMvcAutoConfiguration automatically configures exception handling rules
- Components in container: type: DefaultErrorAttributes -> id: errorAttributes
- DefaultErrorAttributes define what data can be included in the error page
- **Components in the container: type: **BasicErrorController --> id: basicErrorController (json+white page adaptation response)
- Handle requests for the default /error path; the page responds with new ModelAndView( “error” , model);
- There is a component View in the container -> id is error ; (response to the default error page)
- Put the component BeanNameViewResolver (view resolver) in the container; use the returned view name as the component id to find the View object in the container
- **Components in container: **Type: **DefaultErrorViewResolver -> id: **conventionErrorViewResolver
- If an error occurs, the HTTP status code will be used as the view page address (viewName) to find the real page
- error/404、5xx.html
3 exception handling process
1 Execute the target method, any exceptions during the running of the target method will be caught, and mark the end of the current request; and use dispatchException
2 Enter the view parsing process (page rendering)
processDispatchResult(processedRequest, response, mappedHandler, mv, dispatchException);
3 mv = processHandlerException ; Handle the exception that occurred in the handler, and return to ModelAndView after the processing is completed
- Traverse all **handlerExceptionResolvers to see who can handle the current exception [**HandlerExceptionResolver processor exception resolver]
- System default exception parser
- DefaultErrorAttributes handle exceptions first. Save the exception information to the rrequest domain and return null;
- By default no one can handle the exception, so the exception will be thrown
- No one can handle the final bottom layer will send /error request. Will be handled by the underlying BasicErrorController
- Parse the error view; traverse all ErrorViewResolver to see who can resolve it
- The default DefaultErrorViewResolver is used to take the response status code as the address of the error page, error/500.html
- The template engine finally responds to this page error/500.html