2015-01-19 27 views
6

Hiện tại tôi có hai bộ chặn hỗ trợ chức năng tương tự. Tôi muốn hợp nhất chúng.Có phải Spring HandlerInterceptorAdapter postHandle được bảo đảm không?

Một trình chặn là trình ghi nhật ký yêu cầu truy cập, cho biết người dùng đã đăng nhập, id phiên và URL được yêu cầu.

Máy đánh chặn khác là bộ ghi thời gian xử lý.

Trình ghi nhật ký truy cập, để ghi nhật ký tất cả những gì phải được ghi nhật ký, hãy ghi nhật ký yêu cầu trong phương thức preHandle. Ý tưởng là bất kể những gì xảy ra sau (ví dụ: ngoại lệ), yêu cầu truy cập chính xác sẽ có ở đó. Tuy nhiên,

Trình ghi nhật ký thời gian quy trình, do tính chất của nó, phải đăng nhập vào phương thức hậu xử lý.

Để hợp nhất chức năng này, tôi sẽ phải di chuyển mọi thứ vào một phương thức sauHình đơn. Tuy nhiên, có vẻ như tôi có thể mất một số đăng nhập nếu một ngoại lệ xảy ra ở đâu đó, đặc biệt là một ngoại lệ chưa được xử lý đúng trong mã ứng dụng.

Có bất kỳ sự bảo đảm hoặc mô tả nào đối với những cân nhắc này không?

Trả lời

6

Bạn có thể xem xét hợp nhất logic bên trong afterCompletion sẽ được gọi ngay cả trong trường hợp phương thức xử lý phát sinh ngoại lệ. A tốt online example

public class RequestProcessingTimeInterceptor extends HandlerInterceptorAdapter { 

    private static final Logger logger = LoggerFactory 
      .getLogger(RequestProcessingTimeInterceptor.class); 

    @Override 
    public boolean preHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler) throws Exception { 
     long startTime = System.currentTimeMillis(); 
     logger.info("Request URL::" + request.getRequestURL().toString() 
       + ":: Start Time=" + System.currentTimeMillis()); 
     request.setAttribute("startTime", startTime); 
     //if returned false, we need to make sure 'response' is sent 
     return true; 
    } 

    @Override 
    public void postHandle(HttpServletRequest request, 
      HttpServletResponse response, Object handler, 
      ModelAndView modelAndView) throws Exception { 
     System.out.println("Request URL::" + request.getRequestURL().toString() 
       + " Sent to Handler :: Current Time=" + System.currentTimeMillis()); 
     //we can add attributes in the modelAndView and use that in the view page 
    } 

    @Override 
    public void afterCompletion(HttpServletRequest request, 
      HttpServletResponse response, Object handler, Exception ex) 
      throws Exception { 
     long startTime = (Long) request.getAttribute("startTime"); 
     logger.info("Request URL::" + request.getRequestURL().toString() 
       + ":: End Time=" + System.currentTimeMillis()); 
     logger.info("Request URL::" + request.getRequestURL().toString() 
       + ":: Time Taken=" + (System.currentTimeMillis() - startTime)); 
    } 
} 
Các vấn đề liên quan