SlideShare une entreprise Scribd logo
1  sur  25
Télécharger pour lire hors ligne
SERVLET AND JSP FILTERS
Prof. AshishSingh Bhatia
1Prof. AshishSingh Bhatia
What is Filter?
 Filter is a small program that run on the server before the servlet or JSP page with
which it is associated.
 Filter can be attached to one or more servlets or JSP pages and can examine the
request information going into these resources.
 Filter can Invoke the resource in normal manner.
 Filter can Invoke the resource with modified request information.
 Filter can Invoke the resource but modify response before sending it to the client.
 Filter can Prevent resource from being invoked and instead redirect to a different
resource, return a particular status code, or generate replacement output.
Prof. AshishSingh Bhatia 2
What it can be used for ?
 Authentication blocking request based on user identity.
 Logging and auditing – Tracking uses of a web application.
 Image Conversion – Scaling maps and so on.
 Data Compression – Making downloads smaller.
 Localization – Targeting a request and response in particular locale.
 XSL/T Transformation of XML content -
Prof. AshishSingh Bhatia 3
One or many filters
Prof. AshishSingh Bhatia 4
Creating a Basic Filter
1. Create a class that implements the Filter Interface. [ init, doFilter , destroy ]
2. Put the filtering behavior in the doFilter method.
3. Call the doFilter method of the FilterChain object.
4. Register the filter with the appropriate servlets and JSP page.
5. Disable the invoker servlet. **
Prof. AshishSingh Bhatia 5
Create a class that implements the Filter Interface
 Must implement javax.servlet.Filter
 public void init(FilterConfig config) throws ServletException
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain
chain) throws ServletException, IOException
 Executed each time servlet is invoked.
 FilterChain is used to invoke next filter that is associated with the servlet or jsp page, if no more
filters it will invoke servlet or jsp page itself.
 public void destroy()
Prof. AshishSingh Bhatia 6
Register the Filter
 Use filter and filter-mapping tags to register filter in servlet.
<filter>
<filter-name> … </filter-name>
<filter-class> … </filter-class>
</filter>
<filter-mapping>
<filter-name> … </filter-name>
<url-pattern> … </url-pattern>
</filter-mapping>
Prof. AshishSingh Bhatia 7
Understanding filter and mapping tags
 In filter element we can have icon, filter-name, display-name, filter-class, init-param.
 In filter-mapping element filter-name, url-pattern, servlet-name, dispatcher.
 dispatcher : Optional used to specifies what type of request this filter-mapping
should apply to.
 Possible values are REQUEST, FORWARD, INCLUDE and ERROR
Prof. AshishSingh Bhatia 8
Example : Reporting Filter
Prof. AshishSingh Bhatia 9
Code for Servlet
Prof. AshishSingh Bhatia 10
web.xml
Prof. AshishSingh Bhatia 11
Valid too
Prof. AshishSingh Bhatia 12
Better Approach
 Lets log in to the file [ Recall logs directory ]
 For accessing log we need context object.
 context.log(String) to log in to file.
Prof. AshishSingh Bhatia 13
Prof. AshishSingh Bhatia 14
Log File
Prof. AshishSingh Bhatia 15
Initialization Parameter in Filter
 Developers, End Users, Deployers
<filter>
<filter-name>SomeFilter</filter-name>
<filter-class>somePackage.SomeFilterClass</filter-class>
<init-param>
<param-name>param1</param-name>
<param-value>value1</param-value>
</init-param>
</filter>
Prof. AshishSingh Bhatia 16
String val1 = config.getInitParameter("param1");
Example : An Access Time Filter
 To log if access is at unusual time Say if its accessed between 2 to 10 log should be
made.
 To do this two init parameter start time 2 and end time as 10
 In Filter we will read the init parameter as starttime and endtime
 We will get the accessed time as
 GregorianCalendar calendar = new GregorianCalendar();
 int currentTime = calendar.get(Calendar.HOUR_OF_DAY);
 If current time is greater than starttime and less than endtime log will be done.
Prof. AshishSingh Bhatia 17
Blocking the Response
 What we do in a filter
public void doFilter(ServletRequest request,ServletResponse response, FilterChain
chain) throws ServletException, IOException
{
HttpServletRequest req = (HttpServletRequest)request;
context.log(req.getRemoteHost() + " tried to access " +
req.getRequestURL() +" on " + new Date() + ".");
chain.doFilter(request,response);
}
Prof. AshishSingh Bhatia 18
This will call next filter or servlet or jsp
Blocking the Response
public void doFilter(ServletRequest request,ServletResponse response, FilterChain
chain) throws ServletException, IOException
{
HttpServletRequest req = (HttpServletRequest)request;
context.log(req.getRemoteHost() + " tried to access " +
req.getRequestURL() +" on " + new Date() + ".");
if(condition==true)
response.sendRedirect(“some other page / site”);
else
chain.doFilter(request,response);
}
Prof. AshishSingh Bhatia 19
Modifying the response
Prof. AshishSingh Bhatia 20
Filter
doChain(request,response)
Servlet / JSP
Generate Response
And closes the stream !
We will create our own space / buffer
and give it to servlet and can
manipulate the same once Servlet /
JSP is done with response
Creating our Wrapper Class
Prof. AshishSingh Bhatia 21
In Filter Class
Prof. AshishSingh Bhatia 22
In Web.xml
Prof. AshishSingh Bhatia 23
Target will be replace by
replacement
Test.com will be replace by new.com
Modification Method
Prof. AshishSingh Bhatia 24
END OF SESSION
25Prof. AshishSingh Bhatia

Contenu connexe

Tendances (20)

Creational pattern
Creational patternCreational pattern
Creational pattern
 
JNDI
JNDIJNDI
JNDI
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Model View Controller (MVC)
Model View Controller (MVC)Model View Controller (MVC)
Model View Controller (MVC)
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
Adapter Design Pattern
Adapter Design PatternAdapter Design Pattern
Adapter Design Pattern
 
SwiftUI and Combine All the Things
SwiftUI and Combine All the ThingsSwiftUI and Combine All the Things
SwiftUI and Combine All the Things
 
Mvc architecture
Mvc architectureMvc architecture
Mvc architecture
 
interface in c#
interface in c#interface in c#
interface in c#
 
Solid principles
Solid principlesSolid principles
Solid principles
 
Backbone.js
Backbone.jsBackbone.js
Backbone.js
 
Enterprise java unit-3_chapter-1-jsp
Enterprise  java unit-3_chapter-1-jspEnterprise  java unit-3_chapter-1-jsp
Enterprise java unit-3_chapter-1-jsp
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
 
Filter
FilterFilter
Filter
 
Model view controller (mvc)
Model view controller (mvc)Model view controller (mvc)
Model view controller (mvc)
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
CS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptxCS8651 IP Unit 3.pptx
CS8651 IP Unit 3.pptx
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Java Programming - Polymorphism
Java Programming - PolymorphismJava Programming - Polymorphism
Java Programming - Polymorphism
 
Asp.net state management
Asp.net state managementAsp.net state management
Asp.net state management
 

En vedette (20)

01 session tracking
01   session tracking01   session tracking
01 session tracking
 
Lecture 3: Servlets - Session Management
Lecture 3:  Servlets - Session ManagementLecture 3:  Servlets - Session Management
Lecture 3: Servlets - Session Management
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Servlet sessions
Servlet sessionsServlet sessions
Servlet sessions
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Servlet
ServletServlet
Servlet
 
Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Get and post methods
Get and post methodsGet and post methods
Get and post methods
 
Jsp
JspJsp
Jsp
 
Jsp
JspJsp
Jsp
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
Jsp Introduction Tutorial
Jsp Introduction TutorialJsp Introduction Tutorial
Jsp Introduction Tutorial
 
Java servlets
Java servletsJava servlets
Java servlets
 
JSP
JSPJSP
JSP
 
Jsp chapter 1
Jsp chapter 1Jsp chapter 1
Jsp chapter 1
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Jsp presentation
Jsp presentationJsp presentation
Jsp presentation
 
Jsp ppt
Jsp pptJsp ppt
Jsp ppt
 
HTTP Basics
HTTP BasicsHTTP Basics
HTTP Basics
 

Similaire à Servlet Filter

Advanced java programming
Advanced java programmingAdvanced java programming
Advanced java programmingnibiganesh
 
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
Session 3   inter-servlet communication & filters  - Giáo trình Bách Khoa AptechSession 3   inter-servlet communication & filters  - Giáo trình Bách Khoa Aptech
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa AptechMasterCode.vn
 
Advance java session 17
Advance java session 17Advance java session 17
Advance java session 17Smita B Kumar
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...WebStackAcademy
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technologyvikram singh
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1vikram singh
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonJoshua Long
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 

Similaire à Servlet Filter (20)

Advanced java programming
Advanced java programmingAdvanced java programming
Advanced java programming
 
Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Servlet
Servlet Servlet
Servlet
 
Listeners and filters in servlet
Listeners and filters in servletListeners and filters in servlet
Listeners and filters in servlet
 
J2EE-assignment
 J2EE-assignment J2EE-assignment
J2EE-assignment
 
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
Session 3   inter-servlet communication & filters  - Giáo trình Bách Khoa AptechSession 3   inter-servlet communication & filters  - Giáo trình Bách Khoa Aptech
Session 3 inter-servlet communication & filters - Giáo trình Bách Khoa Aptech
 
Advance java session 17
Advance java session 17Advance java session 17
Advance java session 17
 
Advancedservletsjsp
AdvancedservletsjspAdvancedservletsjsp
Advancedservletsjsp
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 9...
 
An Introduction To Java Web Technology
An Introduction To Java Web TechnologyAn Introduction To Java Web Technology
An Introduction To Java Web Technology
 
Web Tech Java Servlet Update1
Web Tech   Java Servlet Update1Web Tech   Java Servlet Update1
Web Tech Java Servlet Update1
 
Filter
FilterFilter
Filter
 
Servlet 3.0
Servlet 3.0Servlet 3.0
Servlet 3.0
 
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy ClarksonMulti Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
 
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U3
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Java servlets
Java servletsJava servlets
Java servlets
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
Servlets
ServletsServlets
Servlets
 

Plus de AshishSingh Bhatia (8)

Servlet Event framework
Servlet Event frameworkServlet Event framework
Servlet Event framework
 
JSP : Creating Custom Tag
JSP : Creating Custom Tag JSP : Creating Custom Tag
JSP : Creating Custom Tag
 
Dom Basics
Dom BasicsDom Basics
Dom Basics
 
Java script
Java scriptJava script
Java script
 
Java I/O Part 2
Java I/O Part 2Java I/O Part 2
Java I/O Part 2
 
Java I/O Part 1
Java I/O Part 1Java I/O Part 1
Java I/O Part 1
 
Nested and Enum Type in Java
Nested and Enum Type in JavaNested and Enum Type in Java
Nested and Enum Type in Java
 
Http and Servlet basics
Http and Servlet basicsHttp and Servlet basics
Http and Servlet basics
 

Dernier

Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docxPoojaSen20
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104misteraugie
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfagholdier
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxAreebaZafar22
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfChris Hunter
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxnegromaestrong
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.MateoGardella
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.pptRamjanShidvankar
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 

Dernier (20)

Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
PROCESS RECORDING FORMAT.docx
PROCESS      RECORDING        FORMAT.docxPROCESS      RECORDING        FORMAT.docx
PROCESS RECORDING FORMAT.docx
 
Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104Nutritional Needs Presentation - HLTH 104
Nutritional Needs Presentation - HLTH 104
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
ICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptxICT Role in 21st Century Education & its Challenges.pptx
ICT Role in 21st Century Education & its Challenges.pptx
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
Making and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdfMaking and Justifying Mathematical Decisions.pdf
Making and Justifying Mathematical Decisions.pdf
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.Gardella_Mateo_IntellectualProperty.pdf.
Gardella_Mateo_IntellectualProperty.pdf.
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 

Servlet Filter

  • 1. SERVLET AND JSP FILTERS Prof. AshishSingh Bhatia 1Prof. AshishSingh Bhatia
  • 2. What is Filter?  Filter is a small program that run on the server before the servlet or JSP page with which it is associated.  Filter can be attached to one or more servlets or JSP pages and can examine the request information going into these resources.  Filter can Invoke the resource in normal manner.  Filter can Invoke the resource with modified request information.  Filter can Invoke the resource but modify response before sending it to the client.  Filter can Prevent resource from being invoked and instead redirect to a different resource, return a particular status code, or generate replacement output. Prof. AshishSingh Bhatia 2
  • 3. What it can be used for ?  Authentication blocking request based on user identity.  Logging and auditing – Tracking uses of a web application.  Image Conversion – Scaling maps and so on.  Data Compression – Making downloads smaller.  Localization – Targeting a request and response in particular locale.  XSL/T Transformation of XML content - Prof. AshishSingh Bhatia 3
  • 4. One or many filters Prof. AshishSingh Bhatia 4
  • 5. Creating a Basic Filter 1. Create a class that implements the Filter Interface. [ init, doFilter , destroy ] 2. Put the filtering behavior in the doFilter method. 3. Call the doFilter method of the FilterChain object. 4. Register the filter with the appropriate servlets and JSP page. 5. Disable the invoker servlet. ** Prof. AshishSingh Bhatia 5
  • 6. Create a class that implements the Filter Interface  Must implement javax.servlet.Filter  public void init(FilterConfig config) throws ServletException  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException  Executed each time servlet is invoked.  FilterChain is used to invoke next filter that is associated with the servlet or jsp page, if no more filters it will invoke servlet or jsp page itself.  public void destroy() Prof. AshishSingh Bhatia 6
  • 7. Register the Filter  Use filter and filter-mapping tags to register filter in servlet. <filter> <filter-name> … </filter-name> <filter-class> … </filter-class> </filter> <filter-mapping> <filter-name> … </filter-name> <url-pattern> … </url-pattern> </filter-mapping> Prof. AshishSingh Bhatia 7
  • 8. Understanding filter and mapping tags  In filter element we can have icon, filter-name, display-name, filter-class, init-param.  In filter-mapping element filter-name, url-pattern, servlet-name, dispatcher.  dispatcher : Optional used to specifies what type of request this filter-mapping should apply to.  Possible values are REQUEST, FORWARD, INCLUDE and ERROR Prof. AshishSingh Bhatia 8
  • 9. Example : Reporting Filter Prof. AshishSingh Bhatia 9
  • 10. Code for Servlet Prof. AshishSingh Bhatia 10
  • 13. Better Approach  Lets log in to the file [ Recall logs directory ]  For accessing log we need context object.  context.log(String) to log in to file. Prof. AshishSingh Bhatia 13
  • 16. Initialization Parameter in Filter  Developers, End Users, Deployers <filter> <filter-name>SomeFilter</filter-name> <filter-class>somePackage.SomeFilterClass</filter-class> <init-param> <param-name>param1</param-name> <param-value>value1</param-value> </init-param> </filter> Prof. AshishSingh Bhatia 16 String val1 = config.getInitParameter("param1");
  • 17. Example : An Access Time Filter  To log if access is at unusual time Say if its accessed between 2 to 10 log should be made.  To do this two init parameter start time 2 and end time as 10  In Filter we will read the init parameter as starttime and endtime  We will get the accessed time as  GregorianCalendar calendar = new GregorianCalendar();  int currentTime = calendar.get(Calendar.HOUR_OF_DAY);  If current time is greater than starttime and less than endtime log will be done. Prof. AshishSingh Bhatia 17
  • 18. Blocking the Response  What we do in a filter public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; context.log(req.getRemoteHost() + " tried to access " + req.getRequestURL() +" on " + new Date() + "."); chain.doFilter(request,response); } Prof. AshishSingh Bhatia 18 This will call next filter or servlet or jsp
  • 19. Blocking the Response public void doFilter(ServletRequest request,ServletResponse response, FilterChain chain) throws ServletException, IOException { HttpServletRequest req = (HttpServletRequest)request; context.log(req.getRemoteHost() + " tried to access " + req.getRequestURL() +" on " + new Date() + "."); if(condition==true) response.sendRedirect(“some other page / site”); else chain.doFilter(request,response); } Prof. AshishSingh Bhatia 19
  • 20. Modifying the response Prof. AshishSingh Bhatia 20 Filter doChain(request,response) Servlet / JSP Generate Response And closes the stream ! We will create our own space / buffer and give it to servlet and can manipulate the same once Servlet / JSP is done with response
  • 21. Creating our Wrapper Class Prof. AshishSingh Bhatia 21
  • 22. In Filter Class Prof. AshishSingh Bhatia 22
  • 23. In Web.xml Prof. AshishSingh Bhatia 23 Target will be replace by replacement Test.com will be replace by new.com
  • 25. END OF SESSION 25Prof. AshishSingh Bhatia