溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

使用spring攔截器實現(xiàn)日志管理實例

發(fā)布時間:2020-10-02 13:06:22 來源:腳本之家 閱讀:141 作者:ctxsdhy 欄目:編程語言

使用HandlerInterceptor攔截器,可以攔截請求,實現(xiàn)通用的日志管理操作

 一、添加攔截器類

在"src/main/java"代碼文件夾的"org.xs.demo1"的包下新建"LogInterceptor.java"類:

package org.xs.demo1;

import java.text.SimpleDateFormat;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import org.springframework.core.NamedThreadLocal;

import org.springframework.web.servlet.HandlerInterceptor;

import org.springframework.web.servlet.ModelAndView; 

/**

 * 日志攔截器

 * @author ThinkGem

 */

public class LogInterceptor implements HandlerInterceptor {
  private final Logger log = LoggerFactory.getLogger(getClass().getName());

  private static final ThreadLocal<Long> startTimeThreadLocal = new NamedThreadLocal<Long>("ThreadLocal StartTime");
  /** 

   * 預(yù)處理

   */

  @Override

  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

     

    long beginTime = System.currentTimeMillis(); //開始時間 

    startTimeThreadLocal.set(beginTime); //線程綁定變量(該數(shù)據(jù)只有當(dāng)前請求的線程可見) 

    log.info("開始計時: {}", new SimpleDateFormat("hh:mm:ss.SSS").format(beginTime));

     

    return true;

  }

  /**

   * 返回處理

   */

  @Override

  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    if (modelAndView != null){

      log.info("ViewName: " + modelAndView.getViewName());

    }

  }

  /**

   * 后處理

   */

  @Override

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

    // 保存日志

    //LogUtils.saveLog(request, handler, ex, null);     

    // 輸出日志信息

    log.info("訪問地址:" + request.getRequestURI() + ",執(zhí)行方式:" + request.getMethod());

    long beginTime = startTimeThreadLocal.get(); //得到線程綁定的局部變量(開始時間) 

    long endTime = System.currentTimeMillis(); //結(jié)束時間 

    log.info("計時結(jié)束:{}", new SimpleDateFormat("hh:mm:ss.SSS").format(endTime)); 

  }
} 

二、修改配置文件

修改spring-mvc.xml件,加入:

<!-- 攔截器配置 -->

<mvc:interceptors>

  <mvc:interceptor>

    <mvc:mapping path="/**" />

    <bean class="org.xs.demo1.LogInterceptor" />

  </mvc:interceptor>

</mvc:interceptors> 

三、運行測試

訪問"http://localhost:8080/demo1/hello/list2"地址

使用spring攔截器實現(xiàn)日志管理實例

可以看到攔截器中輸出的日志信息了

實例代碼地址:spring-HandlerInterceptor_jb51.rar

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI