如何将自己的应用服务器打造成OSS对象存储

前言:

 你有么有想过,怎么才能让自己的应用服务器具有OSS对象存储的功能呢。OSS是收费的,本着白嫖的性质,赶紧撸起代码来。介绍今天的主角 WebMvcConfigurer。存储的文件就是静态文件呀,我们可以通过发布应用,让应用可以通过域名或者ip+端口的形式,去访问应用所在服务器的静态文件,这里就用到了WebMvcConfigurer 的 addResourceHandlers。

是Spring内部的一种配置方式,采用JavaBean的形式来代替传统的xml配置文件形式进行针对框架个性化定制,可以自定义一些Handler,Interceptor,ViewResolver,MessageConverter。基于java-based方式的spring mvc配置,需要创建一个配置类并实现WebMvcConfigurer 接口.

有哪些功能

  1. 通过ViewController将一个请求转到一个页面。

  2. 通过ResourceHandlers实现静态资源的地址映射。

  3. 通过MessageConverter实现将@ResponseBody实体转Fastjson字符串返回,可以返回实体进行重写。

  4. 通过addCorsMappings实现ajax跨域请求。

如何应用

只用一个配置类即可,生成文件在指定目录下,访问指定目录下的文件。就能实现免费的OSS。直接上代码。

需要在pom.xml导包

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

package com.house.config;


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;


/**
* 通用配置
*
* @author
*/
@Configuration
public class ResourcesConfig implements WebMvcConfigurer {


@Override
public void addResourceHandlers(ResourceHandlerRegistry registry)
{
/** 本地文件上传路径 */
registry.addResourceHandler("profile" + "/**")
.addResourceLocations("file:" + "/profile" + "/");
}


/**
* 自定义拦截规则
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {}


/**
* 跨域配置
*/
@Bean
public CorsFilter corsFilter() {
CorsConfiguration config = new CorsConfiguration();
config.setAllowCredentials(true);
// 设置访问源地址
config.addAllowedOrigin("*");
// 设置访问源请求头
config.addAllowedHeader("*");
// 设置访问源请求方法
config.addAllowedMethod("*");
// 有效期 1800秒
config.setMaxAge(1800L);
// 添加映射路径,拦截一切请求
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
source.registerCorsConfiguration("/**", config);
// 返回新的CorsFilter
return new CorsFilter(source);
}
}

声明:文中观点不代表本站立场。本文传送门:https://eyangzhen.com/242927.html

(0)
联系我们
联系我们
分享本页
返回顶部