springboot项目作为静态文件服务器

springboot项目作为静态文件服务器

springboot默认文件作用

使用 spring initialzr 创建 spring boot 项目

https://start.spring.io/

image-20221206214502409

static 存放静态资源

template 存放模板页面 , 例如 thymeleaf

自定义静态文件存放目录

springboot 自动装配 , 默认静态资源的目录是 static

默认还有其它目录

classpath:/META-INF/resources/
classpath:/resources/

classpath:/static/

classpath:/public/

源码

ResourceProperties.java

	private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
			"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

	/**
	 * Locations of static resources. Defaults to classpath:[/META-INF/resources/,
	 * /resources/, /static/, /public/].
	 */
	private String[] staticLocations = CLASSPATH_RESOURCE_LOCATIONS;
....

我们可以自定义

application.properties

spring.resources.static-locations=classpath:/custom/

image-20221206215130583

如图存放的静态资源

测试

引入依赖

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

新建测试 controller

HelloController.java

package com.example.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
public class HelloController {

    private static final String STATIC_FILE = "custom";

    @Value("${server.port}")
    private String port;
    @GetMapping({"/file","/"})
    public String hello(HttpServletResponse response) throws IOException {
        List<String> staticFile = getStaticFile();
        StringBuilder sb = new StringBuilder("");
        for (String s : staticFile) {
            sb.append("<a href=http://"+"localhost:"+port+"/"+s+">");
            sb.append(s);
            sb.append("</a>");
            sb.append("<hr>");
        }
        return sb.toString();
    }

    public List<String> getStaticFile() {
        URL aStatic = this.getClass().getClassLoader().getResource(STATIC_FILE);
        String filePath = aStatic.getFile();
        File file = new File(filePath);
        File[] files = file.listFiles();
        List<String> staticFileList = Arrays.asList(files).stream().map(File::getName).collect(Collectors.toList());
        return staticFileList;
    }
}

测试页面

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-xvRBpVgd-1670335291009)(D:\my-note\typora-picture\image-20221206215521470.png)]

可以查看图片

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-FdC5jrPK-1670335291010)(D:\my-note\typora-picture\image-20221206215534399.png)]

可以下载资源

image-20221206215658550

使用方式

  • 静态资源放在静态文件目录
  • springboot 项目打jar直接部署即可
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Spring Boot项目使用Redis非常简单。以下是使用Redis的步骤: 1. 添加Redis依赖:在项目的pom.xml文件中添加以下依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息:在application.properties或application.yml文件中配置Redis连接信息,例如: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 ``` 3. 创建Redis配置类:创建一个Redis配置类,用于配置Redis连接池和其他相关设置。可以按照以下示例创建一个简单的配置类: ```java @Configuration @EnableCaching public class RedisConfig { @Value("${spring.redis.host}") private String redisHost; @Value("${spring.redis.port}") private int redisPort; @Bean public LettuceConnectionFactory redisConnectionFactory() { RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(redisHost, redisPort); return new LettuceConnectionFactory(config); } @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> template = new RedisTemplate<>(); template.setConnectionFactory(redisConnectionFactory()); return template; } @Bean public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) { RedisCacheConfiguration cacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .disableCachingNullValues(); return RedisCacheManager.builder(redisConnectionFactory) .cacheDefaults(cacheConfiguration) .build(); } } ``` 4. 使用Redis:在需要使用Redis的地方,可以使用@Autowired注解注入RedisTemplate,并使用其提供的方法操作Redis。例如,以下代码演示了如何在Spring Boot中使用Redis进行缓存: ```java @Service public class UserService { @Autowired private RedisTemplate<String, Object> redisTemplate; @Cacheable(value = "users", key = "#userId") public User getUser(String userId) { // 从数据库或其他数据源获取用户信息 User user = userRepository.findById(userId); return user; } @CacheEvict(value = "users", key = "#userId") public void deleteUser(String userId) { // 删除用户信息 userRepository.deleteById(userId); } } ``` 以上是使用Redis的基本步骤,你可以根据实际需求进行更多的配置和使用。希望对你有所帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值