spring boot 错误页,文件上传,异常处理

1.放在resources/static/error下

2.错误页配置

import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

@Configuration
public class ErrorPageConfig {
    @Bean
    public WebServerFactoryCustomizer webServerFactoryCustomizer(){
       return (container -> {
           ErrorPage error401Page = new ErrorPage(HttpStatus.UNAUTHORIZED, "/error/401.html");
           ErrorPage error404Page = new ErrorPage(HttpStatus.NOT_FOUND, "/error/404.html");
           ErrorPage error500Page = new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500.html");
           container.addErrorPages(error401Page, error404Page, error500Page);
       });
    }
}

3.文件上传

#指定上传的文件夹
spring.servlet.multipart.location=e:/springboot
#设置单个文件最大最小
spring.servlet.multipart.max-file-size=5MB
#限制所有文件最大最小
spring.servlet.multipart.max-request-size=20MB
    /*
     *采用spring提供的上传文件的方法
     */
    @RequestMapping("/spring")
    public String  springUpload(Part file) throws MyException {
        String fileName=file.getSubmittedFileName();
        try{
            file.write(fileName);
            return "成功";
        }
        catch(Exception e){
            return "失败";
        }
    }

4.防止大文件上传,拦截器

自定义异常类

​public class MyException extends Exception{
    public MyException(){}
    public MyException(String message){
        super(message);
    }
}

​

文件过大抛出自定义异常

    public class FileUploadInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if(request!=null && ServletFileUpload.isMultipartContent(request)) {
            ServletRequestContext ctx = new ServletRequestContext(request);
            long requestSize = ctx.contentLength();
            if (requestSize > 5*1024*1024) {
                throw new MyException("超了");
            }
        }
        return true;
    }
}

全局异常处理(返回字符串)

@RestControllerAdvice
public class GlobalExceptionHandler {
      @ExceptionHandler(MyException.class)
      public String processException(MyException e) {
        //自定义信息返回给调用端
        return e.getMessage();
      }
}

或者页面(友好方式)

@ControllerAdvice
public class GlobalExceptionHandler {
     @ExceptionHandler(MyException.class)
     //@ResponseBody
     public String processException(MyException e) {
         //自定义信息返回给调用端
         return "error";//templates文件夹下
     }
}

 

你可能感兴趣的:(spring,boot)