博客
关于我
SpringMVC之拦截器与文件上传下载
阅读量:609 次
发布时间:2019-03-13

本文共 3247 字,大约阅读时间需要 10 分钟。

SpringMVC拦截器与文件上传下载

一、拦截器实现

拦截器是SpringMVC框架中的过滤机制,基于AOP思想,用于在控制器方法执行前后或后续处理。实现自定义拦截器需要编写一个类,实现HandlerInterceptor接口,并在配置文件中注册拦截器。

自定义拦截器实现步骤:

  • 实现HandlerInterceptor接口:拦截器必须实现三个方法:

    • preHandle:控制器处理前预处理方法。
    • postHandle:控制器处理后,视图渲染前的后处理方法。
    • afterCompletion:控制器处理完成后,视图渲染后的清理工作。
  • 配置拦截器:在SpringMVC配置文件中使用<mvc:interceptors>标签注册拦截器,指定拦截路径及拦截器类。

  • 配置默认 Servlet 处理静态资源:避免拦截静态资源,配置<mvc:default-servlet-handler>

  • 拦截器示例:

    public class LoginInterceptor implements HandlerInterceptor {    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {        // 检查是否为登录页面        String uri = request.getRequestURI();        if (uri.contains("login")) {            return true;        }                // 检查用户是否已登录        HttpSession session = request.getSession();        if (session.getAttribute("user") != null) {            return true;        }                // 未登录,跳转到登录页面        request.getRequestDispatcher("/login.jsp").forward(request, response);        return false;    }    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,                         ModelAndView modelAndView) throws Exception {        // 可以在这里执行后续处理    }    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,                             Exception e) throws Exception {        // 清理操作,如释放资源    }}

    注册拦截器:

    二、文件上传与下载

    文件上传

  • 前端配置:确保表单使用enctype="multipart/form-data"method="post"

  • SpringMVC配置:配置MultipartResolver。

  • 控制器逻辑

    @RestController@RequestMapping("/upload")class FileController {    @PostMapping("/file")    public String upload(@RequestBody MultipartFile file) throws Exception {        // 读取文件内容并保存        String fileName = file.getOriginalFilename();        if (fileName.isEmpty()) {            return "文件为空";        }        // 保存文件到服务器        File uploadDir = new File("upload/");        if (!uploadDir.exists()) {            uploadDir.mkdirs();        }        File filePath = new File(uploadDir, fileName);        InputStream inputStream = file.getInputStream();        OutputStream outputStream = new FileOutputStream(filePath);        byte[] buffer = new byte[1024];        int byteRead;        while ((byteRead = inputStream.read(buffer)) != -1) {            outputStream.write(buffer, 0, byteRead);            outputStream.flush();        }        outputStream.close();        inputStream.close();        return "文件已上传";    }}
  • 文件下载

  • 控制器方法:返回指定文件的Content-Type和Content-Disposition头。

    @GetMapping("/download")public ResponseEntity
    download(HttpServletResponse response, HttpServletRequest request) { String filename = "example.png"; // 设置响应头 response.setHeader("Content-Disposition", "attachment; filename=" + filename); byte[] content = readResourceFile(filename); return ResponseEntity.ok(content);}
  • 读取文件并返回

    public byte[] readResourceFile(String filename) {    // 读取文件内容    InputStream is = new FileInputStream(new File("resources/" + filename));    return new byte[is.readFile().length];}
  • 注意事项:

    • 文件路径配置:确保服务器上路径存在,防止出错。
    • MultipartResolver配置:严格遵循配置,避免400错误。
    • 字符编码处理:正确设置编码,避免乱码。
    • 安全性:尽量使用非临时目录存储上传文件,避免潜在安全风险。

    转载地址:http://drzaz.baihongyu.com/

    你可能感兴趣的文章
    no available service ‘default‘ found, please make sure registry config corre seata
    查看>>
    No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    查看>>
    no connection could be made because the target machine actively refused it.问题解决
    查看>>
    No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
    查看>>
    No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
    查看>>
    No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
    查看>>
    No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
    查看>>
    No mapping found for HTTP request with URI [/logout.do] in DispatcherServlet with name 'springmvc'
    查看>>
    No module named 'crispy_forms'等使用pycharm开发
    查看>>
    No module named cv2
    查看>>
    No module named tensorboard.main在安装tensorboardX的时候遇到的问题
    查看>>
    No module named ‘MySQLdb‘错误解决No module named ‘MySQLdb‘错误解决
    查看>>
    No new migrations found. Your system is up-to-date.
    查看>>
    No qualifying bean of type XXX found for dependency XXX.
    查看>>
    No qualifying bean of type ‘com.netflix.discovery.AbstractDiscoveryClientOptionalArgs<?>‘ available
    查看>>
    No resource identifier found for attribute 'srcCompat' in package的解决办法
    查看>>
    no session found for current thread
    查看>>
    No toolchains found in the NDK toolchains folder for ABI with prefix: mips64el-linux-android
    查看>>
    NO.23 ZenTaoPHP目录结构
    查看>>
    no1
    查看>>