周振林 周振林
首页
  • 前端文章

    • HTML
    • CSS
    • Tailwind CSS (opens new window)
    • JavaScript
    • Vue3
    • 其他
  • Spring
  • SpringMVC
  • Mybatis
  • 安装教程
  • 其他教程
  • 基础
  • 虚拟化
  • Docker
  • OpenStack
  • 心情杂货
关于
收藏

周振林

IT界的小学生
首页
  • 前端文章

    • HTML
    • CSS
    • Tailwind CSS (opens new window)
    • JavaScript
    • Vue3
    • 其他
  • Spring
  • SpringMVC
  • Mybatis
  • 安装教程
  • 其他教程
  • 基础
  • 虚拟化
  • Docker
  • OpenStack
  • 心情杂货
关于
收藏
  • Spring

  • SpringMVC

    • SpringMVC路径映射
    • SpringMVC请求处理
    • SpringMVC响应请求
      • SpringMVC拦截器
      • SpringMVC过滤器
      • SpringMVC异常
      • SpringBoot数据校验
    • Mybatis

    • 安装教程

    • 其他教程

    • 后端
    • SpringMVC
    周振林
    2025-11-26
    目录

    SpringMVC响应请求

    # SpringMVC响应请求

    实验 内容 目标
    实验1 返回JSON数据 测试对象json写出
    实验2 返回ResponseEntity 测试文件下载
    实验3 引入thymeleaf模板引擎 测试服务端渲染

    # 文件下载

    /**
         * 文件下载
         * HttpEntity:拿到整个请求数据
         * ResponseEntity:拿到整个响应数据(响应头、响应体、状态码)
         */
        @RequestMapping("/download")
        public ResponseEntity<InputStreamResource> download() throws IOException {
    
            //以下代码无需修改
            FileInputStream inputStream = new FileInputStream("C:\\Pictures\\1.jpg");
            //一口气读会溢出
    //        byte[] bytes = inputStream.readAllBytes();
            //1、文件名中文会乱码:解决:
            String encode = URLEncoder.encode("哈哈美女.jpg", "UTF-8");
            
            //2、文件太大会oom(内存溢出)
            InputStreamResource resource = new InputStreamResource(inputStream);
            return ResponseEntity.ok()
                    //内容类型:流
                    .contentType(MediaType.APPLICATION_OCTET_STREAM)
                    //内容大小
                    .contentLength(inputStream.available())
                    //  Content-Disposition :内容处理方式
                    .header("Content-Disposition", "attachment;filename="+encode)
                    .body(resource);
        }
    
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27

    # Thymeleaf模板引擎

    SpringBoot整合的SpringMVC默认不支持JSP

    1. 引入 thymeleaf 作为模型引擎,渲染页面
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    
    1
    2
    3
    4
    1. 默认规则
    • 页面:src/main/resources/templates
    • 静态资源:src/main/resources/static
    Last Updated: 2025/12/02, 11:22:00
    SpringMVC请求处理
    SpringMVC拦截器

    ← SpringMVC请求处理 SpringMVC拦截器→

    最近更新
    01
    查询优化N+1
    12-02
    02
    项目代码组织方式
    12-02
    03
    Mybatis分页插件
    12-02
    更多文章>
    Copyright © 2019-2025 鲁ICP备19032096号-1
    • 跟随系统
    • 浅色模式
    • 深色模式
    • 阅读模式
    ×