SpringMVC进阶

文件上传
  • form表单
  1. form表单的enctype取值必须是multipart/form-data, 默认是application/x-www-form-urlencoded
  2. 请求方式是post
  3. 文件选择域
  • 文件上传原理分析
    enctype为application/x-www-form-urlencoded时,form表单的正文内容是key=value&key=value
    enctype为multipart/form-data时,form表单的正文内容是:
-----------------------------7de1a433602ac      分界符
Content-Disposition: form-data; name="username" 协议头
lisi                                            协议的正文
-----------------------------7de1a433602ac
Content-Disposition: form-data; name="file"; 
filename="C:\test.txt"
Content-Type: text/plain                         协议的类型(MIME 类型)
testeststetestsett
-----------------------------7de1a433602ac--
  • 传统方式文件上传
    传统方式的文件上传,指的是我们上传的文件和访问的应用存在于同一台服务器上
# 依赖
commons-fileupload-1.3.1.jar
commons-io-2.4.jar

a.jsp



FileUploadController.class

@RequestMapping("/fileUpload")
public String fileupload(String name, MultipartFile multipartFile, HttpServletRequest request) throws Exception{

    //1. 原始文件名
    String uploadFileName = multipartFile.getOriginalFilename();
    //2. 截取后缀
    String extName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1, uploadFileName.length());
    //3. 生成新的文件名
    String fileName = "";
    String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
    if(!StringUtils.isEmpty(name)){
        fileName = uuid + "_" + name + "." + extName;
    }else {
        fileName = uuid + "_" + uploadFileName;
    }

    //4.获取文件路径
    ServletContext context = request.getServletContext();
    String basePath = context.getRealPath("/uploads");
    //通过日期解决同一文件夹文件过多的问题
    String datePath = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
    File file = new File(basePath + "/" + datePath);
    if(!file.exists()){
        file.mkdirs();
    }
    //5.上传
    multipartFile.transferTo(new File(file, fileName));
    return "success";
}

配置文件解析器

 

    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     
     
          5242880
    

  • 跨服务器上传文件
# 依赖
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
jersey-client-1.81.1.jar
jersey-core-1.18.1.jar

UploadFileController.class


@RequestMapping("/fileUpload")
public String fileupload(String name, MultipartFile multipartFile, HttpServletRequest request) throws Exception{

    //1. 原始文件名
    String uploadFileName = multipartFile.getOriginalFilename();
    //2. 截取后缀
    String extName = uploadFileName.substring(uploadFileName.lastIndexOf(".")+1, uploadFileName.length());
    //3. 生成新的文件名
    String fileName = "";
    String uuid = UUID.randomUUID().toString().replace("-", "").toUpperCase();
    if(!StringUtils.isEmpty(name)){
        fileName = uuid + "_" + name + "." + extName;
    }else {
        fileName = uuid + "_" + uploadFileName;
    }

    //4.上传
    Client client = Client.create();
    WebResource resource = client.resource("url");
    String result = resource.put(String.class, multipartFile.getBytes());
    System.out.println(result);
    return "success";
}
异常处理
public class CustomException extends Exception {

    private String message;

    public CustomException(String message) {
        this.message = message;
    }

    public String getMessage() {
        return message;
    }
}
public class CustomExceptionResolver implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
        e.printStackTrace();
        CustomException customException = null;
        if(e instanceof CustomException){
            customException = (CustomException)e;
        }else {
            customException = new CustomException("系统错误");
        }
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("message", customException.getMessage());
        modelAndView.setViewName("error");
        return modelAndView;
    }
}
# 配置自定义异常处理类

拦截器

SpringMVC中的拦截器类似于Servlet中的过滤器Filter,用于对处理器进行预处理和后处理
过滤器是Servlet规范中的一部分,任何java web项目都可以使用,通过配置url-pattern,对要访问的资源进行过滤
拦截器是SpringMVC框架的,只有SpringMVC框架的工程才可以使用,只会拦截处理器的方法。
是AOP思想的具体应用

public class MyHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("MyHandlerInterceptor preHandle ......");
        return true; //true就是放行
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("MyHandlerInterceptor postHandle .....");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("MyHandlerInterceptor  afterCompletion ......");
    }
}
    
        
             
            
            
        
    

你可能感兴趣的:(SpringMVC进阶)