【Java从零到架构师第③季】【44】SpringBoot-SpringMVC


持续学习&持续更新中…

守破离


SpringMVC的配置1

在这里插入图片描述

SpringMVC的配置2

org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties

在这里插入图片描述

spring:
  mvc:
    servlet:
      load-on-startup: 0
    format:
      #      默认
      #      date: dd/MM/yyyy
      date: yyyy-MM-dd
      date-time: yyyy-MM-dd HH:mm:ss

文件上传

在这里插入图片描述

spring:
  servlet:
    multipart:
      max-file-size: 10MB
      max-request-size: 100MB

SpringBoot项目的文件保存路径需要自己手动指定,但是我们肯定不能将路径硬编码到代码中,可以使用application.yml:

project:
  uploads:
    base-path: D:/uploads/
    image-path: image/
    video-path: video/
    others-path: others/
@Component
@Data
@AllArgsConstructor
@NoArgsConstructor
@ConfigurationProperties("project")
public class ProjectProperties {

    private Uploads uploads;

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public static class Uploads {
        private String basePath;
        private String imagePath;
        private String videoPath;
        private String othersPath;
    }

}
	<dependency>
	    <groupId>commons-io</groupId>
	    <artifactId>commons-io</artifactId>
	    <version>2.6</version>
	</dependency>
@RestController
@RequestMapping("/test")
public class TestController {
    @Autowired
    private ProjectProperties projectProperties;

    @PostMapping("/fileUpload")
    public String fileUpload(MultipartFile file) throws Exception {
        final ProjectProperties.Uploads uploads = projectProperties.getUploads();
        final String basePath = uploads.getBasePath();
        final String imagePath = uploads.getImagePath();
        final String fileName = file.getOriginalFilename();
//        final String fileName = UUID.randomUUID() + "." + FilenameUtils.getExtension(file.getOriginalFilename());
        File destFile = new File(basePath + imagePath + fileName);
        // 确保目标文件所在的目录存在
        // destFile.getParentFile().mkdirs();
        FileUtils.forceMkdirParent(destFile);
        file.transferTo(destFile);
        return "success";
    }

}

静态资源访问

在这里插入图片描述

静态资源访问—映射

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

在这里插入图片描述

静态资源访问—映射本质

在这里插入图片描述

@Configuration
public class SpringMVCConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("file:///D:/uploads/");
    }
}

相比于application.yml还可以灵活的这样写:

@Configuration
public class SpringMVCConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                .addResourceLocations("classpath:/static/");

        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:///D:/uploads/");
    }
}

静态资源访问—映射webjars

前端的很多东西就是静态资源,比如jQuery的js文件、…,我们可以直接在项目中引用它们,这个时候就可以使用webjars技术了。

官网:https://www.webjars.org/

在这里插入图片描述

	<dependency>
	    <groupId>org.webjars</groupId>
	    <artifactId>jquery</artifactId>
	    <version>3.5.1</version>
	</dependency>
<button type="button" id="btn-add">添加</button>

<!--<script th:src="@{/webjars/jquery/3.5.1/jquery.js}"></script>-->
<script th:src="@{/webjars/jquery/3.5.1/jquery.min.js}"></script>

<script>
    $('#btn-add').click(() => {
        alert('点击了添加')
    })
</script>

org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration.WebMvcAutoConfigurationAdapter源码:

		@Override
		public void addResourceHandlers(ResourceHandlerRegistry registry) {
			if (!this.resourceProperties.isAddMappings()) {
				logger.debug("Default resource handling disabled");
				return;
			}
			addResourceHandler(registry, "/webjars/**", "classpath:/META-INF/resources/webjars/");
			addResourceHandler(registry, this.mvcProperties.getStaticPathPattern(), (registration) -> {
				registration.addResourceLocations(this.resourceProperties.getStaticLocations());
				if (this.servletContext != null) {
					ServletContextResource resource = new ServletContextResource(this.servletContext, SERVLET_LOCATION);
					registration.addResourceLocations(resource);
				}
			});
		}

文件下载

在这里插入图片描述

<a th:href="@{/test.txt}">访问test.txt文件</a>

<a th:href="@{/download}">以附件的形式下载test.txt文件</a>
    @GetMapping("/download")
    public void download(HttpServletResponse response) throws Exception {
        // 把文件以附件的形式返回

        // 设置响应头
        response.setHeader("Content-Disposition", "attachment; filename=test.txt");

        // 读取文件
        try (InputStream is = new ClassPathResource("static/test.txt").getInputStream()) {
            // 将文件数据利用response写回到客户端
            IOUtils.copy(is, response.getOutputStream());
        }
    }

参考

小码哥-李明杰: Java从0到架构师③进阶互联网架构师.


本文完,感谢您的关注支持!


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值