1. 程式人生 > >27.Spring-Boot中攔截器中靜態資源的處理(踩過坑)以及Spring mvc configuring拓展介紹

27.Spring-Boot中攔截器中靜態資源的處理(踩過坑)以及Spring mvc configuring拓展介紹

一.springboot中對靜態資源的處理

 預設情況下,springboot提供存放放置靜態資源的資料夾:

 /static 

/public  

/resources 

/META-INF/resources

對於maven專案即就是存在src/main/resources 資料夾下。

 如圖:static資料夾就是springboot中預設的資料夾

在頁面中這樣寫路徑<link href="themes/bootstrap.min.css" rel="stylesheet" type="text/css"/>這塊就不用寫static檔案夾了。

於此同時我們也可以修改springboot預設的存放靜態資料夾存放路徑用 spring.mvc.static-path-pattern=/resources/** 。

在springboot中新增攔截器是不會認springboot中的靜態資料夾的路徑的,所以在設定攔截器的時候應該從springboot預設的靜態檔案算起。

具體程式碼如下:

靜態檔案存放路徑還如上圖

1.定義攔截器

package com.niugang.filter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LogInterceptor implements HandlerInterceptor {
private static Logger logger = LoggerFactory.getLogger(LogInterceptor.class);
    /**
     * 執行攔截器之前
     */
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
logger.info("interceptor....在執行前...url:{}", request.getRequestURL());
return true; //返回false將不會執行了
}

      /**
* 呼叫完處理器,渲染檢視之前
*/
@Override
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
logger.info("interceptor.......url:{}", request.getRequestURL());
}


@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
}
}

2.配置攔截器

package com.niugang.config;
import java.util.concurrent.TimeUnit;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import com.niugang.filter.LogInterceptor;
@Configuration
@EnableWebMvc
public class MvcConfig extends WebMvcConfigurerAdapter {
/**
* 授權攔截的路徑 addPathPatterns:攔截的路徑 excludePathPatterns:不攔截的路徑
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new LogInterceptor()).addPathPatterns("/**").excludePathPatterns("/login/**",
"/static/*");
super.addInterceptors(registry);
}

     /**
* 修改springboot中預設的靜態檔案路徑
*/
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//addResourceHandler請求路徑
//addResourceLocations 在專案中的資源路徑
//setCacheControl 設定靜態資源快取時間
registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
super.addResourceHandlers(registry);
}
}

3.頁面引入

<link href="static/themes/bootstrap.min.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="static/script/jquery.min.js" ></script>
<!--layer彈出框-->
<link rel="stylesheet" href="static/script/layer/mobile/need/layer.css" type="text/css">
<script type="text/javascript" src="static/script/layer/layer.js" ></script>

這樣就可以正常訪問了。

二。spring mvc configuring配置介紹

MVC Java config和MVC名稱空間提供了類似的預設配置,可以覆蓋DispatcherServlet預設配置。目標是讓大多數應用程式不必建立相同的配置,併為配置Spring MVC提供更高級別的構造,而Spring MVC作為一個簡單的起點,並且不需要事先知道底層配置的知識。

您可以根據您的偏好選擇MVC Java config或MVC名稱空間。此外,您還將看到,在MVC Java配置下,更容易看到底層配置,並直接對建立的Spring MVC bean進行細粒度定製。

1.MVC Java配置

啟用MVC Java配置需要@EnableWebMvc 和 @Configuration註解在類上


@Configuration
@EnableWebMvc
public class WebConfig {
 

}


上面的配置如XML中的

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd"
>
<mvc:annotation-driven/>
</beans>

開啟上面配置,底層其實開啟了很多預設的配置,如果訊息轉換,時間格式化,欄位檢驗與轉化。

2.自定義配置

要自定義Java的預設配置,只需實現WebMvcConfigurer介面。或者更可能擴充套件類WebMvcConfigurerAdapter並覆蓋您需要的方法推薦使用重寫WebMvcConfigurerAdapter:

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
// Override configuration methods...
}
這樣你可以重寫很多方法,就如剛才程式碼,重寫了配置靜態資源,和新增攔截器。

具體其他的方法可以看原始碼註釋

三:HTTP Cache 對靜態資源的支援

靜態資源應該使用適當的“Cache-Control”和有條件的標題來實現最佳效能。配置ResourceHttpRequestHandler用於服務靜態資源,不僅可以通過讀取檔案的元資料來編寫“Last-Modified”的標題,而且如果配置正確,還可以“Cache-Control”頭。

@Configuration
@EnableWebMvc
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler(
"/resources/**")
.addResourceLocations(
"/public-resources/")
.setCacheControl(CacheControl.maxAge(1, TimeUnit.HOURS).cachePublic());
}
}

                                                                               微信公眾號: 

                                               

                                                                             JAVA程式猿成長之路

                                                       分享學習資源,學習方法,記錄程式設計師生活。