You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

82 lines
3.2 KiB

package cc.bnblogs.config;
import cc.bnblogs.common.LRUCache;
import cc.bnblogs.interceptor.LoginInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.ConfigurableWebServerFactory;
import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.io.File;
/**
* @author zfp@bnblogs.cc
* @createTime: 2022/10/16
*/
@Slf4j
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Value("${upload.base-dir}")
private String baseDir;
@Override
public void addInterceptors(InterceptorRegistry registry) {
// 注册拦截器,添加拦截路由和放行路由
registry.addInterceptor(loginInterceptor)
.addPathPatterns("/admin/**")
.excludePathPatterns("/admin/login","/admin/logout","/admin/login.html");
}
private final LoginInterceptor loginInterceptor;
public static final Integer MAX_LRU_CACHE_SIZE = 20;
public WebConfig(LoginInterceptor loginInterceptor) {
this.loginInterceptor = loginInterceptor;
}
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 创建static目录到/static/的路由
// 即改为localhost:8080/static/image/1.jpg. 而不是原来的localhost:8080/image/1.jpg
registry.addResourceHandler("/static/**").
addResourceLocations("classpath:/static/");
File dir = new File(baseDir);
if (!dir.isDirectory()) {
// 创建文件保存目录
dir.mkdirs();
}
String absolutePath = dir.getAbsolutePath().replace("./", "") + "/";
log.info("absolutePath:{}", absolutePath);
// 一定要在绝对路径前加上file://表明它是一个本地目录
// !!!!!!
// 记住在absolutePath前加一个'/',否则本地图片读取不出来(重要的事情说三遍)
registry.addResourceHandler("/upload/**").addResourceLocations("file://" + '/' + absolutePath);
}
/**
* 错误页面配置是根据HTTP请求返回的状态码决定的(Http异常)
* Controller层的报错是thymeleaf渲染页面时报错的(业务异常)
* @return 跳转到对应的error页面
*/
@Bean
public WebServerFactoryCustomizer<ConfigurableWebServerFactory> webServerFactoryCustomizer() {
return factory -> factory.addErrorPages(
new ErrorPage(HttpStatus.NOT_FOUND, "/error/404.html"),
new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/error/500.html"));
}
@Bean
public LRUCache lruCache() {
return new LRUCache(MAX_LRU_CACHE_SIZE);
}
}