SpringBoot2 靜態檔案的處理
阿新 • • 發佈:2019-01-24
處理方式
對於靜態檔案一般我們會引入諸如bootstrap和jq等一些前段的UI框架,我們通常的使用方法是放到靜態資料夾之中。另一種我們可以新增webjar檔案進行使用
使用:直接映入pom檔案,然後在前段去使用
<!--jq-->
<dependency>
<groupId>org.webjars</groupId>
<artifactId>jquery</artifactId>
<version>3.3.1-1</version>
</dependency>
<script type="text/javascript" src="/webjars/jquery/3.3.1-1/jquery.js"></script>
問題: 如果我們自己寫一點css和js怎麼辦? 因為會被攔截
一、自定義一個攔截器
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// 自定義的靜態資源攔截器
public class ResourceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o,
ModelAndView modelAndView) throws Exception {
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse,
Object o, Exception e) throws Exception {
}
}
二、將攔截器注入spring容器
import com.springboot.crud.interceptor.ResourceInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class ResourceConfig implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new ResourceInterceptor()).excludePathPatterns("/static/**");
}
@Override
//需要告知系統,這是要被當成靜態檔案的!
public void addResourceHandlers(ResourceHandlerRegistry registry) {
// 設定檔案上傳的檔案不攔截
// registry.addResourceHandler("/upload/**").addResourceLocations("file:"+ TaleUtils.getUplodFilePath()+"upload/");
//第一個方法設定訪問路徑字首,第二個方法設定資源路徑
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
}
}
三、前段使用
<link rel="stylesheet" href="/static/bootstrap3.3.7/css/bootstrap.css">
<link rel="stylesheet" href="/static/bootstrap3.3.7/css/bootstrap-theme.css">
<link rel="stylesheet" href="/static/bootstrap3.3.7/css/bootstrap-datetimepicker.min.css">
<script type="text/javascript" src="/webjars/jquery/3.3.1-1/jquery.js"></script>
靜態資原始檔需要放到 src/main/resources/static 目錄下。