2.静态资源访问&文件上传&拦截器

文章介绍了SpringBoot中静态资源的存放路径及访问方式,通过`spring.mvc.static-path-pattern`和`spring.web.resources.static-locations`进行配置。接着展示了文件上传的示例代码,文件保存在`upload/`目录下,并提到SpringBoot内嵌Tomcat对文件上传大小的限制及如何修改这些限制。最后,文章讨论了使用拦截器实现权限控制,创建`LoginInterceptor`并配置到SpringBoot应用中,以限制普通用户访问特定资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

静态资源访问

Web程序中静态资源放在哪里,又该如何访问。不设置可不能这么访问哦

默认是不加static的

spring.mvc.static-path-pattern=/static/**
spring.web.resources.static-locations=classpath:/static/

文件上传

@RestController
public class FileController {
    private static final String UPLOADED_FOLDER = System.getProperty("user.dir") + "/upload/";
    @PostMapping("/upload")
    public String upload(String nickname, MultipartFile f) throws IOException {
        System.out.println("文件大小" + f.getSize());
        System.out.println(f.getContentType());
        System.out.println(f.getOriginalFilename());
        System.out.println(System.getProperty("user.dir"));
        saveFile(f);
        return "上传成功";
    }

    private void saveFile(MultipartFile f) throws IOException {
        File upDir = new File(UPLOADED_FOLDER);
        if(!upDir.exists()) {
            upDir.mkdir();
        }
        File file = new File((UPLOADED_FOLDER+f.getOriginalFilename()));
        f.transferTo(file);
    }
}

Spring Boot工程嵌入的tomcat限制了请求的文件大小,每个文件的配置最大为1Mb,单次请求的文件的总数不能大于10Mb。

要更改这个默认值需要在配置文件(如application.properties)中加入两个配置

拦截器

有时候,我们不想让普通用户访问特殊资源,此刻就需要了拦截器

创建一个拦截器

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }
}

创建,Spring配置类让拦截器生效

@Configuration
public class Webconfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**");
    }
}

目录结构如下所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值