springMvc中實現攔截器Interceptor以及添加靜態資源映射


這個代碼寫了很久了,多久呢?2018年12-20號寫的。。。。

廢話不多說,簡化一下,作為筆記。

注:

public class springmvcConfig extends WebMvcConfigurerAdapter 這種寫法已廢棄,WebMvcConfigurerAdapter不再推薦使用。

 

1:新建一個攔截器類,實現 HandlerInterceptor 接口 

 1 class InterceptorConfig implements HandlerInterceptor {
 2     private static final Logger log = LoggerFactory.getLogger(Filter.class);
 3 
 4     /**
 5      * httpServletRequest存儲請求信息,如ip地址,url等
 6      * preHandle進入Handler方法之前執行了,使用於身份認證,身份授權,登陸校驗等,比如身份認證,用戶沒有登陸,
 7      * 攔截不再向下執行,返回值為 false ,即可實現攔截;否則,返回true時,攔截不進行執行
 8      **/
 9     @Override
10     public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
11         String ip = httpServletRequest.getRemoteAddr();
12         String url = httpServletRequest.getRequestURI();
13         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
14         Date date = new Date();
15         String time = sdf.format(date);
16         log.info("時間:{},IP地址:{},目標URL:{}", time, ip, url);
17 
18         return true;
19     }
20 
21     /**
22      * 進入Handler方法之后,返回ModelAndView之前執行,使用場景從ModelAndView參數出發,
23      * 比如,將公用的模型數據在這里傳入到視圖,也可以統一指定顯示的視圖等
24      **/
25     @Override
26     public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
27         log.info("i am in hendler before return modelandview...");
28 
29     }
30 
31     /**
32      * 在執行Handler完成后執行此方法,使用於統一的異常處理,統一的日志處理等
33      **/
34     @Override
35     public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
36         log.info("i am out of from handler...");
37 
38     }
39 }

 

2:新建一個mvc配置類實現 WebMvcConfigurer 接口,並加上 @Configuration 聲明其為配置類:

 

@Configuration
public class SpringmvcConfig implements WebMvcConfigurer{
    private static final Logger log = LoggerFactory.getLogger(SpringmvcConfig.class);
    //圖片映射
    @Value("${images.path}")
    private String imagesRoot;

   //添加靜態資源映射 @Override
public void addResourceHandlers(ResourceHandlerRegistry registry) { log.info("圖片靜態資源路徑:{}", imagesRoot);
     registry.addResourceHandler("/images/**").addResourceLocations(imagesRoot); }
   //添加攔截器 @Override
public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new InterceptorConfig()); } }

 

 

3:最后上截圖,並標明攔截器的個方法執行順序,如圖:

1:執行Prehandler

2:執行Controller中的代碼

3:在返回ModelAndView之前執行postHandler

4:最后執行afterCompletion

 

 

 若有不對望指正免得無人子弟,覺得寫得可以的同學點個贊哦~

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM