{"id":3297,"date":"2019-04-07T16:36:27","date_gmt":"2019-04-07T16:36:27","guid":{"rendered":"http:\/\/codethataint.com\/blog\/?p=3297"},"modified":"2020-09-24T10:52:34","modified_gmt":"2020-09-24T10:52:34","slug":"filters-vs-handlers","status":"publish","type":"post","link":"https:\/\/codethataint.com\/blog\/filters-vs-handlers\/","title":{"rendered":"Filters vs Interceptors"},"content":{"rendered":"<p><strong class=\"ctaHeader2\">Filters<\/strong> <\/p>\n<ol>\n<li>A <strong>filter <\/strong>as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same way is possible to manage HTTP outbound response after resource execution.\n<\/li>\n<li>The filter runs in the web container so its definition will also be contained in the web.xml file<\/li>\n<li>filer include three main methods:\n<ul>\n<li>init: executed to initialize filter using init-param element in filter definition<\/li>\n<li>doFilter: executed for all HTTP incoming request that satisfy &#8220;url-pattern&#8221;<\/li>\n<li>release resources used by the filter<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/codethataint.com\/blog\/wp-content\/uploads\/2019\/04\/filter.png\" height=\"285\" width=\"940\"\/><\/p>\n<p><strong>web.xml<\/strong><\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;filter&gt;\r\n    &lt;filter-name&gt;CORSFilter&lt;\/filter-name&gt;\r\n    &lt;filter-class&gt;com.listfeeds.components.CORSFilter&lt;\/filter-class&gt;\r\n    &lt;init-param&gt;\r\n        &lt;param-name&gt;fake-param&lt;\/param-name&gt;\r\n        &lt;param-value&gt;fake-param-value&lt;\/param-value&gt;\r\n    &lt;\/init-param&gt;\r\n&lt;\/filter&gt;\r\n&lt;filter-mapping&gt;\r\n    &lt;filter-name&gt;CORSFilter&lt;\/filter-name&gt;\r\n    &lt;url-pattern&gt;\/*&lt;\/url-pattern&gt;\r\n&lt;\/filter-mapping&gt;\r\n<\/pre>\n<p><strong>TestFilter.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npackage com.listfeeds.filters;\r\n\r\nimport java.io.IOException;\r\nimport javax.servlet.Filter;\r\nimport javax.servlet.FilterChain;\r\nimport javax.servlet.FilterConfig;\r\nimport javax.servlet.ServletException;\r\nimport javax.servlet.ServletRequest;\r\nimport javax.servlet.ServletResponse;\r\nimport javax.servlet.http.HttpServletResponse;\r\nimport org.springframework.stereotype.Component;\r\n\r\npublic class TestFilter implements Filter {\r\n\r\n    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {\r\n\r\n        HttpServletResponse response = (HttpServletResponse) res;\r\n        response.setHeader(&quot;Access-Control-Allow-Origin&quot;, &quot;*&quot;);\r\n        response.setHeader(&quot;Access-Control-Allow-Methods&quot;, &quot;POST, GET, OPTIONS, DELETE&quot;);\r\n        response.setHeader(&quot;Access-Control-Max-Age&quot;, &quot;3600&quot;);\r\n        response.setHeader(&quot;Access-Control-Allow-Headers&quot;, &quot;x-requested-with&quot;);\r\n        chain.doFilter(req, res);\r\n    }\r\n\r\n    public void init(FilterConfig filterConfig) {}\r\n\r\n    public void destroy() {}\r\n\r\n}\r\n<\/pre>\n<p>Filters can perform many different types of functions. <\/p>\n<ol>\n<li>  Authentication-Blocking requests based on user identity.<\/li>\n<li>  Logging and auditing-Tracking users of a web application.<\/li>\n<li>  Image conversion-Scaling maps<\/li>\n<li>  Data compression-Making downloads smaller<\/li>\n<li>  Localization-Targeting the request and response to a particular locale<\/li>\n<\/ol>\n<p>Request Filters can:<\/p>\n<ol>\n<li>perform security checks<\/li>\n<li>reformat request headers or bodies<\/li>\n<li>audit or log requests<\/li>\n<\/ol>\n<p>Response Filters can:<\/p>\n<ol>\n<li>Compress the response stream<\/li>\n<li>Append or alter the response stream<\/li>\n<li>Create a different response altogether<\/li>\n<\/ol>\n<p><strong class=\"ctaHeader2\">Interceptors<\/strong> <\/p>\n<ol>\n<li>Spring <strong>Interceptors<\/strong> are similar to Servlet Filters but they acts in Spring Context so are many powerful to manage HTTP Request and Response but they can implement more sophisticated behavior because can access to all Spring context.<\/li>\n<li> Developers can invoke interceptor methods in conjunction with method invocations or lifecycle events on an associated target class. Common uses of interceptors are logging, auditing, or profiling.<\/li>\n<li>Spring interceptor execute in Spring context so they have be defined in rest-servlet.xml file:<\/li>\n<li>The interceptor include three main methods:\n<ul>\n<li>preHandle: executed before the execution of the target resource<\/li>\n<li>afterCompletion: executed after the execution of the target resource (after rendering the view)<\/li>\n<li>posttHandle: Intercept the execution of a handler<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p><strong>rest-servlet.xml<\/strong><\/p>\n<pre class=\"brush: xml; title: ; notranslate\" title=\"\">\r\n&lt;mvc:interceptors&gt;\r\n    &lt;bean class=&quot;com.listfeeds.interceptors.LogContextInterceptor&quot; \/&gt;\r\n    &lt;bean class=&quot;com.listfeeds.interceptors.TimedInterceptor&quot; \/&gt;\r\n&lt;\/mvc:interceptors&gt;\r\n<\/pre>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"http:\/\/codethataint.com\/blog\/wp-content\/uploads\/2019\/04\/interceptor.png\" height=\"384\" width=\"1055\"\/><\/p>\n<p><strong>LogContextInterceptor.java<\/strong><\/p>\n<pre class=\"brush: java; title: ; notranslate\" title=\"\">\r\npublic class LogContextInterceptor extends HandlerInterceptorAdapter \r\n{\r\n private static final Logger log = LoggerFactory.getLogger(LogContextInterceptor.class);\r\n\r\n @Override\r\n public void afterCompletion(\r\n  HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)\r\n throws Exception \r\n {\r\n  HandlerMethod methodHandler = (HandlerMethod) handler;\r\n  log.debug(&quot;END EXECUTION method {} request: {}&quot;, methodHandler.getMethod().getName(), request.getRequestURI());\r\n  }\r\n \r\n\r\n @Override\r\n public boolean preHandle(HttpServletRequest request,\r\n  HttpServletResponse response, Object handler) throws Exception \r\n  {\r\n\r\n  } catch (IllegalArgumentException e) \r\n  {\r\n   log.warn(&quot;Prehandle&quot;, e);\r\n   return true;\r\n  } finally \r\n  {\r\n   HandlerMethod methodHandler = (HandlerMethod) handler;\r\n   log.debug(&quot;START EXECUTION method {} request: {}&quot;, methodHandler.getMethod().getName(), request.getRequestURI());\r\n  }\r\n  return true;\r\n}\r\n<\/pre>\n<p><strong>For authentication of web pages you would use a servlet filter which acts at weblayer. For security stuff in your business layer or logging\/bugtracing (a.k.a. independent of the web layer) you would use an Interceptor.<\/strong><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Filters A filter as the name suggests is a Java class executed by the servlet container for each incoming http request and for each http response. This way, is possible to manage HTTP incoming requests before them reach the resource, such as a JSP page, a servlet or a simple static page; in the same&hellip; <a href=\"https:\/\/codethataint.com\/blog\/filters-vs-handlers\/\">Continue reading <span class=\"meta-nav\">&rarr;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[273],"tags":[],"class_list":["post-3297","post","type-post","status-publish","format-standard","hentry","category-spring-mvc"],"_links":{"self":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3297","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/comments?post=3297"}],"version-history":[{"count":5,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3297\/revisions"}],"predecessor-version":[{"id":3926,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/posts\/3297\/revisions\/3926"}],"wp:attachment":[{"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/media?parent=3297"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/categories?post=3297"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/codethataint.com\/blog\/wp-json\/wp\/v2\/tags?post=3297"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}