SlideShare a Scribd company logo
Implementing Filter
Agenda
• Exploring the need of filter
• Exploring filter API
• Creating a Filter
• Configuring a Filter
• Using initialization parameter in Filters
The Need for Filter
• Servlet Filters are Java classes that can be used in Servlet
Programming for the following purposes:
- To intercept requests from a client before they
access a resource at back end.
- To manipulate responses from server before they
are sent back to the client.
Types of Filter suggested
• Authentication Filters.
• Data compression Filters
• Encryption Filters .
• Filters that trigger resource access events.
• Image Conversion Filters .
• Logging and Auditing Filters.
• MIME-TYPE Chain Filters.
• Tokenizing Filters .
• XSL/T Filters That Transform XML Content
Exploring the Filter API
• Defined in javax.servlet.* package
- Filter
- FilterChain
- FilterConfig
• We define the filter by implementing the Filter interface
• FilterChain is passed to a filter by Container for invoking the series of
Filter
• FilterConfig contains initialization data if required
Exploring the Filter interface
• Filter interface contains doFilter method which is the heart of filter
• It usually performs the following action
- Examines the request header
- Customizes the request Object (like header,data etc)
- Customizes the response object(like header, data etc)
Creating a Filter
• Basic format
public void doFilter(ServletRequest request,
ServletResponse response,
FilterChain chain)
throws ServletException, IOException {
…
chain.doFilter(request,response);
}
• Note on first two arguments
- They are of type ServletRequest and ServletResponse, not HttpServletRequest
and HttpServletResponse.
• Do a typecast if you need HTTP-specific capabilities
Simple Report Filter
public class ReportFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws ServletException, IOException {
HttpServletRequest req = (HttpServletRequest)request;
System.out.println(req.getRemoteHost() +" tried to access " +
req.getRequestURL() +
" on "+new Date() + ".");
chain.doFilter(request,response);
}
public void init(FilterConfig config) throws ServletException { }
public void destroy() {}
}
Registering the Filter in web.xml
<web-app>
<!-- Register the name "Reporter” for ReportFilter. -->
<filter>
<filter-name>Reporter</filter-name>
<filter-class>moreservlets.filters.ReportFilte</filter-class>
</filter>
Important note
Servers load filters into memory when the Web app first comes up. So,
if that filter is not found, your entire Web app is disabled.
Associating Reporting with given URL’s
<!-- Apply Reporter filter to home page. -->
<filter-mapping>
<filter-name>Reporter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
<!-- Also apply Reporter filter to servlet named "TodaysSpecial". -->
<filter-mapping>
<filter-name>Reporter</filter-name>
<servlet-name>TodaysSpecial</servlet-name>
</filter-mapping>
</web-app>
Using initialization Parameter for Filter
• Filter can be configured to use initialization parameters like a normal
servlet like
- <init-param>
- <context-param>
• <init-param>
- Use FilterConfig inside init method to read the parameters
• <context-param>
- Using FilterConfig need to obtain ServletContext.
- Read the parameter from the ServletContext thus obtained
Advantages of Filter
• Encapsulate common behavior.
- Have 30 different servlets or JSP pages that need to compress their
content to decrease download time? Make 1 compression filter and
apply it to all 30 resources.
• Separate high-level access decisions from presentation code.
- Want to block access from certain sites without modifying the
individual pages to which these access restrictions apply? Create an
access restriction filter and apply it to as many pages as you like.
• Apply wholesale changes to many different resources.
- Have a bunch of existing resources that should remain unchanged
except that the company name should be changed? Make a string
replacement filter and apply it wherever appropriate.
Summary
• Implement the Filter interface
• Override doFilter, init, and destroy
- init and destroy are often empty
• Declare filter in web.xml
- Give it a name and designate URLs to which it applies
• Accessing the servlet context
- Look it up in init, store it in a field
• Filters have init parameters
• Blocking resources
- Simply omit call to FilterChain.doFilter
• Modifying response
- Pass a wrapper to resource, invoke resource, extract output from wrapper,
modify it, pass it to client..

More Related Content

PPTX
Integrate ManifoldCF with Solr
PDF
Servlet Filter
PDF
Jackrabbit setup configuration
PPTX
Servlet Filters
PPTX
How to get full power from WebApi
PPTX
Real World Asp.Net WebApi Applications
PPTX
Introduction to Lucene and Solr - 1
PDF
.NET Core, ASP.NET Core Course, Session 9
Integrate ManifoldCF with Solr
Servlet Filter
Jackrabbit setup configuration
Servlet Filters
How to get full power from WebApi
Real World Asp.Net WebApi Applications
Introduction to Lucene and Solr - 1
.NET Core, ASP.NET Core Course, Session 9

What's hot (15)

PPTX
Repository design pattern in laravel
PDF
The Good, the Bad and the Ugly of Java API design
PPTX
Servlets - filter, listeners, wrapper, internationalization
PDF
Codeigniter Training Part3
PDF
The good, the bad, and the ugly of Java API design
PPTX
NiFi - First approach
PDF
An Empirical Study on the Use and Misuse of Java 8 Streams
PPTX
Xitrum internals
PPTX
Solr introduction
PDF
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
PPT
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
PDF
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
PDF
Webinar: What's New in Solr 7
TXT
Codigo java
PDF
Fossil scm overview
Repository design pattern in laravel
The Good, the Bad and the Ugly of Java API design
Servlets - filter, listeners, wrapper, internationalization
Codeigniter Training Part3
The good, the bad, and the ugly of Java API design
NiFi - First approach
An Empirical Study on the Use and Misuse of Java 8 Streams
Xitrum internals
Solr introduction
Lifecycle of a Solr Search Request - Chris "Hoss" Hostetter, Lucidworks
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
Safe Automated Refactoring for Intelligent Parallelization of Java 8 Streams ...
Webinar: What's New in Solr 7
Codigo java
Fossil scm overview
Ad

Similar to Advance java session 17 (20)

PPTX
Advanced java programming
PPTX
Servlet session 12
PPTX
Filter
PPTX
Filter
PPTX
Session 5 - Working withAFTER Filters.pptx
PPTX
PDF
Servlet
PDF
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
PPT
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
PDF
Ch. 13 filters and wrappers
PDF
Advancedservletsjsp
PPT
Listeners and filters in servlet
PDF
Introduction tomcat7 servlet3
PPT
Java - Servlet - Mazenet Solution
PDF
Sling Component Filters in CQ5
PDF
Servlets
PPT
Web Technologies -- Servlets 4 unit slides
PPTX
servlets sessions and cookies, jdbc connectivity
PPTX
Introduction to Servlets topic for https
PDF
Bt0083 server side programing
Advanced java programming
Servlet session 12
Filter
Filter
Session 5 - Working withAFTER Filters.pptx
Servlet
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
GAC Java Presentation_Server Side Include_Cookies_Filters 2022.ppt
Ch. 13 filters and wrappers
Advancedservletsjsp
Listeners and filters in servlet
Introduction tomcat7 servlet3
Java - Servlet - Mazenet Solution
Sling Component Filters in CQ5
Servlets
Web Technologies -- Servlets 4 unit slides
servlets sessions and cookies, jdbc connectivity
Introduction to Servlets topic for https
Bt0083 server side programing
Ad

More from Smita B Kumar (20)

PPTX
Advance java session 20
PPTX
Advance java session 19
PPTX
Advance java session 18
PPTX
Advance java session 16
PPTX
Advance java session 15
PPTX
Advance java session 14
PPTX
Advance java session 13
PPTX
Advance java session 12
PPTX
Advance java session 11
PPTX
Advance java session 10
PPTX
Advance java session 9
PPTX
Advance java session 8
PPTX
Advance java session 7
PPTX
Advance java session 6
PPTX
Advance java session 5
PPTX
Advance java session 4
PPTX
Advance java session 3
PPTX
Advance java session 2
PPTX
JEE session 1
PPTX
01 introduction to struts2
Advance java session 20
Advance java session 19
Advance java session 18
Advance java session 16
Advance java session 15
Advance java session 14
Advance java session 13
Advance java session 12
Advance java session 11
Advance java session 10
Advance java session 9
Advance java session 8
Advance java session 7
Advance java session 6
Advance java session 5
Advance java session 4
Advance java session 3
Advance java session 2
JEE session 1
01 introduction to struts2

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Approach and Philosophy of On baking technology
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Encapsulation_ Review paper, used for researhc scholars
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Electronic commerce courselecture one. Pdf
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PDF
Unlocking AI with Model Context Protocol (MCP)
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Empathic Computing: Creating Shared Understanding
PPTX
Programs and apps: productivity, graphics, security and other tools
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Mobile App Security Testing_ A Comprehensive Guide.pdf
PDF
cuic standard and advanced reporting.pdf
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Approach and Philosophy of On baking technology
Advanced methodologies resolving dimensionality complications for autism neur...
Encapsulation_ Review paper, used for researhc scholars
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Electronic commerce courselecture one. Pdf
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Unlocking AI with Model Context Protocol (MCP)
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
The Rise and Fall of 3GPP – Time for a Sabbatical?
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Empathic Computing: Creating Shared Understanding
Programs and apps: productivity, graphics, security and other tools
20250228 LYD VKU AI Blended-Learning.pptx
Building Integrated photovoltaic BIPV_UPV.pdf
Mobile App Security Testing_ A Comprehensive Guide.pdf
cuic standard and advanced reporting.pdf

Advance java session 17

  • 2. Agenda • Exploring the need of filter • Exploring filter API • Creating a Filter • Configuring a Filter • Using initialization parameter in Filters
  • 3. The Need for Filter • Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes: - To intercept requests from a client before they access a resource at back end. - To manipulate responses from server before they are sent back to the client.
  • 4. Types of Filter suggested • Authentication Filters. • Data compression Filters • Encryption Filters . • Filters that trigger resource access events. • Image Conversion Filters . • Logging and Auditing Filters. • MIME-TYPE Chain Filters. • Tokenizing Filters . • XSL/T Filters That Transform XML Content
  • 5. Exploring the Filter API • Defined in javax.servlet.* package - Filter - FilterChain - FilterConfig • We define the filter by implementing the Filter interface • FilterChain is passed to a filter by Container for invoking the series of Filter • FilterConfig contains initialization data if required
  • 6. Exploring the Filter interface • Filter interface contains doFilter method which is the heart of filter • It usually performs the following action - Examines the request header - Customizes the request Object (like header,data etc) - Customizes the response object(like header, data etc)
  • 7. Creating a Filter • Basic format public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { … chain.doFilter(request,response); } • Note on first two arguments - They are of type ServletRequest and ServletResponse, not HttpServletRequest and HttpServletResponse. • Do a typecast if you need HTTP-specific capabilities
  • 8. Simple Report Filter public class ReportFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; System.out.println(req.getRemoteHost() +" tried to access " + req.getRequestURL() + " on "+new Date() + "."); chain.doFilter(request,response); } public void init(FilterConfig config) throws ServletException { } public void destroy() {} }
  • 9. Registering the Filter in web.xml <web-app> <!-- Register the name "Reporter” for ReportFilter. --> <filter> <filter-name>Reporter</filter-name> <filter-class>moreservlets.filters.ReportFilte</filter-class> </filter> Important note Servers load filters into memory when the Web app first comes up. So, if that filter is not found, your entire Web app is disabled.
  • 10. Associating Reporting with given URL’s <!-- Apply Reporter filter to home page. --> <filter-mapping> <filter-name>Reporter</filter-name> <url-pattern>/index.jsp</url-pattern> </filter-mapping> <!-- Also apply Reporter filter to servlet named "TodaysSpecial". --> <filter-mapping> <filter-name>Reporter</filter-name> <servlet-name>TodaysSpecial</servlet-name> </filter-mapping> </web-app>
  • 11. Using initialization Parameter for Filter • Filter can be configured to use initialization parameters like a normal servlet like - <init-param> - <context-param> • <init-param> - Use FilterConfig inside init method to read the parameters • <context-param> - Using FilterConfig need to obtain ServletContext. - Read the parameter from the ServletContext thus obtained
  • 12. Advantages of Filter • Encapsulate common behavior. - Have 30 different servlets or JSP pages that need to compress their content to decrease download time? Make 1 compression filter and apply it to all 30 resources. • Separate high-level access decisions from presentation code. - Want to block access from certain sites without modifying the individual pages to which these access restrictions apply? Create an access restriction filter and apply it to as many pages as you like. • Apply wholesale changes to many different resources. - Have a bunch of existing resources that should remain unchanged except that the company name should be changed? Make a string replacement filter and apply it wherever appropriate.
  • 13. Summary • Implement the Filter interface • Override doFilter, init, and destroy - init and destroy are often empty • Declare filter in web.xml - Give it a name and designate URLs to which it applies • Accessing the servlet context - Look it up in init, store it in a field • Filters have init parameters • Blocking resources - Simply omit call to FilterChain.doFilter • Modifying response - Pass a wrapper to resource, invoke resource, extract output from wrapper, modify it, pass it to client..