29 Ekim 2019 Salı

SpringMVC HandlerInterceptor Arayüzü

Giriş
Şu satırı dahil ederiz. Bu arayüzü gerçekleştiren sınıflardan birisi HandlerInterceptorAdapter 
import org.springframework.web.servlet.HandlerInterceptor;
Bu arayüz aslında bir advice gerçekleştirimi için. Tek farkı @ControllerAdvice yerine bu arayüzden kalıtıyoruz. Açıklaması şöyle. Request ve Response nesnelerini değiştirmek için uygun değil dense de bence çok uygun.
Basically, Interceptor is similar to a Servlet Filter, but in contrast to the latter, It is located after DispatcherServlet and as a result, related HandlerInterceptor class configured inside the application context. Filters are known to be more powerful, they are allowed to exchange the request and response objects that are handed down the chain whereas, Interceptors are just allowed to add some custom pre-processing, option of prohibiting the execution, and also custom post-processing.
Şeklen şöyle



Genel Kullanım
Interceptor, InterceptorRegistry nesnesine eklenir.

Örnek
Şöyle yaparız
@Component
public class CustomWebConfigurer implements WebMvcConfigurer {

  @Autowired
  private InterceptLog logInterceptor;

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(logInterceptor);
  }
}

@Component
public class InterceptLog implements HandlerInterceptor {

   
  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, 
    Object handler) throws Exception {
    if(request.getMethod().equals(HttpMethod.GET.name())
      || request.getMethod().equals(HttpMethod.DELETE.name())
      || request.getMethod().equals(HttpMethod.PUT.name()))    {
        ...
    }
    return true;
  }
}
Örnek - URL
Eğer sadece belli bir URL için eklemek istersek şöyle yaparız
@Configuration
public class WebConfig implements WebMvcConfigurer {

  @Override
  public void addInterceptors(InterceptorRegistry registry) {
    registry.addInterceptor(new LogInterceptor() )
            .addPathPatterns("/student/*");;
  }
}
Örnek - URL
Eğer Interceptor'lar arasında sıra belirtmek istersek şöyle yaparız
@Override
public void addInterceptors(InterceptorRegistry registry) {
  registry.addInterceptor(new LogInterceptor()).order(1);
  registry.addInterceptor(new AuthenticationInterceptor()).order(2);
}

preHandle - HttpServletRequest + HttpServletResponse + handle
Açıklaması şöyle. Yani isteği kesmek için uygun bir nokta
This method will be called before sending the request to the controller. Returning false in this method will stop the process from passing the request to the controller
Örnek
Request nesnesine yeni bir özellik ekleyen HandlerInterceptor  için şöyle yaparız.
@Slf4j
public class LogInterceptor implements HandlerInterceptor {

  @Override
  public boolean preHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler) throws Exception {
    UUID uuid = UUID.randomUUID();
    request.setAttribute("start" , System.currentTimeMillis());
    request.setAttribute("request-id", uuid );
    log.info( "{} - calling {}" , uuid , request.getRequestURI() );
    return true;
  }

  @Override
  public void postHandle( HttpServletRequest request,
                          HttpServletResponse response,
                          Object handler,
                         ModelAndView modelAndView) throws Exception {
    log.info( "{} - response in {}ms", 
      request.getAttribute("request-id"),  
      System.currentTimeMillis() - (long) request.getAttribute("start") );
   }

  @Override
  public void afterCompletion(HttpServletRequest request,
                              HttpServletResponse response,
                              Object handler,
                              Exception exception) throws Exception {
    log.info( "{} - completed in {}ms", 
      request.getAttribute("request-id"),  
      System.currentTimeMillis() - (long) request.getAttribute("start") );
  }
}
postHandle metodu
Açıklaması şöyle
This method will be used to perform operations before sending the response to the client.
afterCompletion metodu
Açıklaması şöyle
This method will be used for operations after the whole cycle was completed and the view is generated


Hiç yorum yok:

Yorum Gönder