Giriş
Interceptor bir Spring kavramı, Filter ise bir Servlet kavramı. WebRequestInterceptor sınıfları HandlerInterceptor sınıflarından daha sonra çalışır. Açıklaması şöyle
HandlerInterceptor's method take HttpServletRequest, HttpServletResponse, Object(handler) ...while WebRequestInterceptor take WebRequest (a wrapper of HttpServletRequest).
Bu arayüzün amacı HttpRequest vs ile uğraşmak değil, daha üst seviye işler yapmak. Açıklaması şöyle
One of the canonical use cases of WebRequestInterceptor is preparing context resources (such as a Hibernate Session) and expose them as request attributes or as thread-local objects. Also, you can modify those context resources after successful handler execution (for example, flushing a Hibernate Session). For example, OpenEntityManagerInViewInterceptor binds a JPA EntityManager to the thread for the entire processing of the request....WebRequestInterceptor interface is deliberately minimalistic to keep the dependencies of generic request interceptors as minimal as feasible. If you need to change the response, you should use HandlerIntercepter or Filters.
afterCompletion metodu - WebRequest + Exception
Örnek ver
preHandle metodu - WebRequest
Şöyle yaparız. Http isteğindeki bir alanı okur ve thread local bir değişkene atar
ThreadLocal sınıf şöyledir@Slf4j@Componentpublic class TenantInterceptor implements WebRequestInterceptor {private static final String TENANT_HEADER = "X-Tenant";@Overridepublic void preHandle(WebRequest request) {String tenantId = request.getHeader(TENANT_HEADER);if (tenantId != null && !tenantId.isEmpty()) {TenantContext.setTenantId(tenantId);log.info("Tenant header get: {}", tenantId);} else {log.error("Tenant header not found.");throw new TenantAliasNotFoundException("Tenant header not found.");}}@Overridepublic void postHandle(WebRequest webRequest, ModelMap modelMap) {TenantContext.clear();}@Overridepublic void afterCompletion(WebRequest webRequest, Exception e) {}}
@Slf4jpublic class TenantContext {private static final ThreadLocal<String> CONTEXT = new ThreadLocal<>();public static void setTenantId(String tenantId) {log.debug("Setting tenantId to " + tenantId);CONTEXT.set(tenantId);}public static String getTenantId() {return CONTEXT.get();}public static void clear() {CONTEXT.remove();}}
postHandle metodu - WebRequest + ModelMap
Açıklaması şöyle. İstek işlenmiş, model hazırlamış ancak daha view döndürülmemiştir.
postHandle will be called after handler method invocation but before the view being rendered.
Hiç yorum yok:
Yorum Gönder