SlideShare une entreprise Scribd logo
1  sur  41
Filters, Listeners, Wrappers, Internationalization.	 By, Susnatsahu
Filters Filters concept has introduced in Servlet 2.3 version. A filter is a program that runs on the server before the Servlet or JSP page with which it is associated. A filter can be attached to one or more Servlet or JSP pages and can examine the request information going into these resources. Filters are used to preprocess the Request and post process the Response.
Preprocessing involves  ,[object Object]
Logging,
Authorization,
Change request information , etc..Post processing involves  ,[object Object]
Encryption of the response.
To alter response information.Other Tasks ,[object Object]
Session validation
Internationalization
Data compression
MIME type changing,[object Object]
The filter class encapsulates the logic that has to be executed before or after the actual request processing, which is done by the requested resources.
The filter class is declared in the deployment descriptor.
It provides the ability to encapsulate recurring tasks in reusable units., Which allows us to modularize the code, which makes the code more manageable, documentable, easy to debug, and can be reused in other settings. ,[object Object]
The Filter Life Cycle
Lets know about Filter API 		This API comprises of three interfaces  ,[object Object]
javax.servlet.FilterConfig
javax.servlet.FilterChainjavax.servlet.Filter 	Every Filter class must implement Filter interface either directly or indirectly.
void init(FilterConfig filterConfig)   ,[object Object]
 The Servlet container calls the init method exactly once after instantiating the filter.
The web container cannot place the filter into service if the init method either1. Throws a ServletException 2. Does not return within a time period defined by the web container
void doFilter (ServletRequestrequest, ServletResponse response, FilterChain chain) 	Encapsulates service logic to be implemented on ServletRequest to generate the ServletResponse.  	The FilterChain referncepassed as an argument to forwardrequest/response pair to the filter or targetresource of chain.  void destroy( )  	Called by the web container to indicate to a filter that it is being taken out of service.
[object Object]
Used during initialization of filter.
This object is used to fetch configuration information specified in web.xml
 String getFilterName()           Returns the filter-name of this filter as defined in the deployment descriptor. 
String getInitParameter(String name)           Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. ,[object Object]
[object Object],The object of this interface stores information about a chain of filters.  Void doFilter(ServletRequest request, ServletResponse response)           Causes the next filter in the chain to be invoked, or if the calling filter is the last filter in the chain, causes the resource at the end of the chain to be invoked. Container doesn’t call this method. We have to call it explicitly. chain.doFilter( request, response);
How to apply a filter – In web.xml  Or <url-pattern>*</url-pattern> (in 2.5) <servlet-name>/---Action</servlet-name> <filter> 	<filter-name>LogFilter</filter-name>  	<filter-class>LogFilter</filter-class>  	      <init-param> 		 <param-name>uname</param-name> 		 <param-value>scott</param-value>  	      </init-param>  </filter>  <filter-mapping>  	<filter-name>LogFilter</filter-name>  	<url-pattern>/####.jsp</url-pattern>  </filter-mapping>
What are the possible ways for a Servlet to  get a request ? Direct end-user request (REQUEST) (2.3 ver) By RequestDispatcher forward (FORWARD) By RequestDispatcher include (INCLUDE) By error page call (ERROR) 	Java servlet 2.4 specification sun introduced <dispatcher> tag to extend filter concept for last 3 calls also.
REQUEST – This is default value. Filter will only execute only on end user request. FORWARD - Filter will only execute for RequestDispatcher forward calls. <filter-mapping>  	<filter-name>LogFilter</filter-name>  	<url-pattern>*</url-pattern> 	<dispatcher>REQUEST</dispatcher>  	<dispatcher>FORWARD</dispatcher> </filter-mapping>
INCLUDE – Filter will only execute for 				    RequestDispatcher include calls. ERROR - Filter will only execute for error page calls. <filter-mapping>  	<filter-name>LogFilter</filter-name>  	<url-pattern>/report.jsp</url-pattern> 	<dispatcher>ERROR</dispatcher> </filter-mapping> <error-page>   <exception-type>java.lang.ArithmeticException</exception-type> 	<location>/index.jsp</location> </error-page>
In the context of web application there may be chances of occurring several events like –   Request object creation Session object destruction Context object creation  Adding attribute in request scope  Removing attribute from application scope etc.. Listeners The servlet specification includes the capability to track key events in your Web applications through event listeners.
Listeners are classified on the basis of  event types. Events can be of  the request, session, application level scope. The listener interfaces are in javax.servlet package :  Request Listeners :  ,[object Object]
ServletRequestAttributeListenerContext Listeners : ,[object Object]
ServletContextAttributeListener,[object Object]
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListenerServletRequestListener : 		This listener listens lifecycle events of request object. It has two methods.  void requestInitialized(ServletRequestEvent  rre) : 		This method will executed automatically at the time  of request object creation  i.e. before starting service method
void requestDestroyed(ServletRequestEvent rre)  This method will executed automatically at the time  of request object destroyed. ServletRequestAttributeListener :  This listener listens events related to request scoped attributes. It has 3 methods. void attributeAdded(ServletRequestAttributeEvent srae) void attributeRemoved(ServletRequestAttributeEvent srae) void attributeReplaced(ServletRequestAttributeEvent srae)

Contenu connexe

Tendances

Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Vibhawa Nirmal
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applicationsNiyas Nazar
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycleDhruvin Nakrani
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web APIBrad Genereaux
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST APIAmilaSilva13
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#Hemant Chetwani
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods pptkamal kotecha
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in JavaSonya Akter Rupa
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jspJafar Nesargi
 
Java Collections API
Java Collections APIJava Collections API
Java Collections APIAlex Miller
 
JSP Processing
JSP ProcessingJSP Processing
JSP ProcessingSadhana28
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network SecurityKathirvel Ayyaswamy
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSINGINTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSINGAaqib Hussain
 

Tendances (20)

Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface) Introduction to APIs (Application Programming Interface)
Introduction to APIs (Application Programming Interface)
 
Servlets
ServletsServlets
Servlets
 
Vulnerabilities in modern web applications
Vulnerabilities in modern web applicationsVulnerabilities in modern web applications
Vulnerabilities in modern web applications
 
Servlet and servlet life cycle
Servlet and servlet life cycleServlet and servlet life cycle
Servlet and servlet life cycle
 
Introduction to the Web API
Introduction to the Web APIIntroduction to the Web API
Introduction to the Web API
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
introduction about REST API
introduction about REST APIintroduction about REST API
introduction about REST API
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Properties and indexers in C#
Properties and indexers in C#Properties and indexers in C#
Properties and indexers in C#
 
Java servlet life cycle - methods ppt
Java servlet life cycle - methods pptJava servlet life cycle - methods ppt
Java servlet life cycle - methods ppt
 
Restful web services ppt
Restful web services pptRestful web services ppt
Restful web services ppt
 
Method Overloading in Java
Method Overloading in JavaMethod Overloading in Java
Method Overloading in Java
 
Chapter 3 servlet & jsp
Chapter 3 servlet & jspChapter 3 servlet & jsp
Chapter 3 servlet & jsp
 
Java Collections API
Java Collections APIJava Collections API
Java Collections API
 
JSP Processing
JSP ProcessingJSP Processing
JSP Processing
 
Web api
Web apiWeb api
Web api
 
18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security18CS2005 Cryptography and Network Security
18CS2005 Cryptography and Network Security
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSINGINTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE  AND JSP PROCESSING
INTRODUCTION TO JSP,JSP LIFE CYCLE, ANATOMY OF JSP PAGE AND JSP PROCESSING
 
Session tracking In Java
Session tracking In JavaSession tracking In Java
Session tracking In Java
 

En vedette

Java Servlets
Java ServletsJava Servlets
Java ServletsEmprovise
 
Cyber Crime & Information technology Act 2000
Cyber Crime & Information technology Act 2000Cyber Crime & Information technology Act 2000
Cyber Crime & Information technology Act 2000V'vek Sharma
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jspAnkit Minocha
 
It act 2000 & cyber crime 111111
It act 2000 & cyber crime 111111It act 2000 & cyber crime 111111
It act 2000 & cyber crime 111111Yogendra Wagh
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagramsbarney92
 

En vedette (9)

Java Servlet
Java Servlet Java Servlet
Java Servlet
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
interface in c#
interface in c#interface in c#
interface in c#
 
Cyber fraud
Cyber fraudCyber fraud
Cyber fraud
 
Cyber Crime & Information technology Act 2000
Cyber Crime & Information technology Act 2000Cyber Crime & Information technology Act 2000
Cyber Crime & Information technology Act 2000
 
1 java servlets and jsp
1   java servlets and jsp1   java servlets and jsp
1 java servlets and jsp
 
Uml - An Overview
Uml - An OverviewUml - An Overview
Uml - An Overview
 
It act 2000 & cyber crime 111111
It act 2000 & cyber crime 111111It act 2000 & cyber crime 111111
It act 2000 & cyber crime 111111
 
Uml diagrams
Uml diagramsUml diagrams
Uml diagrams
 

Similaire à Servlets - filter, listeners, wrapper, internationalization

Advanced java programming
Advanced java programmingAdvanced java programming
Advanced java programmingnibiganesh
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4Ben Abdallah Helmi
 
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
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18Smita B Kumar
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2Santosh Singh Paliwal
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packagesvamsi krishna
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Arun Gupta
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T Spatinijava
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servletssbd6985
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9aminmesbahi
 

Similaire à Servlets - filter, listeners, wrapper, internationalization (20)

Chap4 4 1
Chap4 4 1Chap4 4 1
Chap4 4 1
 
Advanced java programming
Advanced java programmingAdvanced java programming
Advanced java programming
 
SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4SCWCD : The servlet container : CHAP : 4
SCWCD : The servlet container : CHAP : 4
 
Servlet
ServletServlet
Servlet
 
Advancedservletsjsp
AdvancedservletsjspAdvancedservletsjsp
Advancedservletsjsp
 
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...
 
Advance java session 18
Advance java session 18Advance java session 18
Advance java session 18
 
What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2What is the difference between struts 1 vs struts 2
What is the difference between struts 1 vs struts 2
 
Javax.servlet,http packages
Javax.servlet,http packagesJavax.servlet,http packages
Javax.servlet,http packages
 
Filter
FilterFilter
Filter
 
Filter
FilterFilter
Filter
 
ajava unit 1.pptx
ajava unit 1.pptxajava unit 1.pptx
ajava unit 1.pptx
 
J2EE-assignment
 J2EE-assignment J2EE-assignment
J2EE-assignment
 
WEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES ServletWEB TECHNOLOGIES Servlet
WEB TECHNOLOGIES Servlet
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
 
S E R V L E T S
S E R V L E T SS E R V L E T S
S E R V L E T S
 
UNIT-3 Servlet
UNIT-3 ServletUNIT-3 Servlet
UNIT-3 Servlet
 
.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9.NET Core, ASP.NET Core Course, Session 9
.NET Core, ASP.NET Core Course, Session 9
 
Wt unit 3
Wt unit 3 Wt unit 3
Wt unit 3
 
Servlet 3.0
Servlet 3.0Servlet 3.0
Servlet 3.0
 

Dernier

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
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfAyushMahapatra5
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdfQucHHunhnh
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Dernier (20)

Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
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 ...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
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
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Class 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdfClass 11th Physics NEET formula sheet pdf
Class 11th Physics NEET formula sheet pdf
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
1029 - Danh muc Sach Giao Khoa 10 . pdf
1029 -  Danh muc Sach Giao Khoa 10 . pdf1029 -  Danh muc Sach Giao Khoa 10 . pdf
1029 - Danh muc Sach Giao Khoa 10 . pdf
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
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
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).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
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
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"
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

Servlets - filter, listeners, wrapper, internationalization

  • 1. Filters, Listeners, Wrappers, Internationalization. By, Susnatsahu
  • 2. Filters Filters concept has introduced in Servlet 2.3 version. A filter is a program that runs on the server before the Servlet or JSP page with which it is associated. A filter can be attached to one or more Servlet or JSP pages and can examine the request information going into these resources. Filters are used to preprocess the Request and post process the Response.
  • 3.
  • 6.
  • 7. Encryption of the response.
  • 8.
  • 12.
  • 13. The filter class encapsulates the logic that has to be executed before or after the actual request processing, which is done by the requested resources.
  • 14. The filter class is declared in the deployment descriptor.
  • 15.
  • 17.
  • 19. javax.servlet.FilterChainjavax.servlet.Filter Every Filter class must implement Filter interface either directly or indirectly.
  • 20.
  • 21. The Servlet container calls the init method exactly once after instantiating the filter.
  • 22. The web container cannot place the filter into service if the init method either1. Throws a ServletException 2. Does not return within a time period defined by the web container
  • 23. void doFilter (ServletRequestrequest, ServletResponse response, FilterChain chain) Encapsulates service logic to be implemented on ServletRequest to generate the ServletResponse. The FilterChain referncepassed as an argument to forwardrequest/response pair to the filter or targetresource of chain. void destroy( )  Called by the web container to indicate to a filter that it is being taken out of service.
  • 24.
  • 26. This object is used to fetch configuration information specified in web.xml
  • 27.  String getFilterName()           Returns the filter-name of this filter as defined in the deployment descriptor. 
  • 28.
  • 29.
  • 30. How to apply a filter – In web.xml Or <url-pattern>*</url-pattern> (in 2.5) <servlet-name>/---Action</servlet-name> <filter> <filter-name>LogFilter</filter-name> <filter-class>LogFilter</filter-class> <init-param> <param-name>uname</param-name> <param-value>scott</param-value> </init-param> </filter> <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/####.jsp</url-pattern> </filter-mapping>
  • 31. What are the possible ways for a Servlet to get a request ? Direct end-user request (REQUEST) (2.3 ver) By RequestDispatcher forward (FORWARD) By RequestDispatcher include (INCLUDE) By error page call (ERROR) Java servlet 2.4 specification sun introduced <dispatcher> tag to extend filter concept for last 3 calls also.
  • 32. REQUEST – This is default value. Filter will only execute only on end user request. FORWARD - Filter will only execute for RequestDispatcher forward calls. <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>*</url-pattern> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping>
  • 33. INCLUDE – Filter will only execute for RequestDispatcher include calls. ERROR - Filter will only execute for error page calls. <filter-mapping> <filter-name>LogFilter</filter-name> <url-pattern>/report.jsp</url-pattern> <dispatcher>ERROR</dispatcher> </filter-mapping> <error-page> <exception-type>java.lang.ArithmeticException</exception-type> <location>/index.jsp</location> </error-page>
  • 34. In the context of web application there may be chances of occurring several events like – Request object creation Session object destruction Context object creation Adding attribute in request scope Removing attribute from application scope etc.. Listeners The servlet specification includes the capability to track key events in your Web applications through event listeners.
  • 35.
  • 36.
  • 37.
  • 40. HttpSessionActivationListenerServletRequestListener : This listener listens lifecycle events of request object. It has two methods. void requestInitialized(ServletRequestEvent  rre) : This method will executed automatically at the time of request object creation i.e. before starting service method
  • 41. void requestDestroyed(ServletRequestEvent rre) This method will executed automatically at the time of request object destroyed. ServletRequestAttributeListener : This listener listens events related to request scoped attributes. It has 3 methods. void attributeAdded(ServletRequestAttributeEvent srae) void attributeRemoved(ServletRequestAttributeEvent srae) void attributeReplaced(ServletRequestAttributeEvent srae)
  • 42.
  • 43. HttpSessionListener : Related to life cycle of the session objects. void sessionCreated(HttpSessionEvent se) void sessionDestroyed(HttpSessionEvent se)
  • 44. public class Log4jListener implements ServletContextListener { public void contextDestroyed(ServletContextEvent arg0) { } public void contextInitialized(ServletContextEvent event) { String drive=System.getenv("HOMEDRIVE"); String separator=System.getProperty("file.separator"); String logfolder =drive+separator+"MyApps"+ separator+"logs"+ separator; File file=new File(logfolder); if(!file.exists()) file.mkdirs(); }} <servlet> <servlet-name>Log4jAction</servlet-name> <servlet-class>com.eias.logging.Log4jAction </servlet-class> <init-param> <param-name>log4j-properties-location</param-name> <param-value>WEB-INFroperties og4j.properties </param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <listener> <listener-class>com.eias.logging.Log4jListener</listener-class> </listener>
  • 45. wrapper Whenever you want to create a custom request or response object, just subclass one of the convinces request or response “wrapper” classes. A wrapper wraps the real request or response object, and passes through calls to the real thing, while still you do the extra things you need for your custom request or response. The benefit of wrapping comes from custom coding a particular wrapping object to manipulate a request or response in a way not normally done.
  • 46. What are the core objects of servlet API ? ServletRequest ServletResponse HttpServletRequest HttpServletResponse
  • 47.
  • 52.
  • 53. Import javax.servlet.*; Public class MyRequestWrapper extends ServletRequestWrapper{ Public MyRequestWrapper (ServletRequestreq) { Super(req); } public String getParameter(String S) { String s1=super.getParameter(s); if(s1==null) s1=“ NONE ”; return s1; } }
  • 54. Import javax.servlet.*; Public class MyWrapperFilter implements Filter { Public void init(FilterConfigfc) { } ; Public void destroy() { } ; Public void doFilter(ServletRequestreq, ServletResponse res, FilterChain chain) throws SE, IO … { MyRequestWrapper wrapperReq= new MyRequestWrapper (); Chian.doFilter(wrapperReq, res); } } Wrapped request object
  • 55. Internationalization : It can be defined as the process of enabling a web application to present different country and region specific formats without making any changes to the code or recompiling the application. This term generally abbreviated as i18n. Localization : This is a process of of customizing a software or web apps for a specific region or language. Known as l10n
  • 56. locale:  This is a particular cultural or geographical region. It is usually referred to as a language symbol followed by a country symbol which are separated by an underscore. For example "en_US" represents English locale for US. java.util.Locale class is used while creating international java application. It is a non-abstract final class. A Locale object represents a specific geographical, language, or cultural region locale. These locale affect language choice, collation, calendar usage, date and time formats number and currency formats etc..
  • 57. Create a Locale object using the constructors in this class: Locale(String language) Locale(String language, String country) Locale(String language, String country, String variant) Ex – Locale myLocale=new Locale(“en”,”US”); String getCountry()This method returns the country/region code in upper case for this locale in ISO 3166 2-letter format.
  • 58. String getLanguage()This method returns the language code in lower case for this locale in ISO 639 format.  String getVariant()           Returns the variant code for this locale.A ResourceBundle is like a specialized form of a Hashtable that maps strings to values. the magic of ResourceBundle allows you to have different lookup tables based upon what Locale (language/country) a user is coming in from.
  • 59. ResourceBundle class This class is used to separate localizable elements such as button labels , error messages, and headings from rest of the application. ResourceBundle "knows" how to search the hierarchy for a locale-appropriate instance, getBundle(String baseName) getBundle(String baseName, Locale locale) This is a abstract class. Two direct subclasses are : PropertyResourceBundle - commonly used. ListResourceBundle
  • 60.
  • 62. Numbersrb_fr.properties# Default properties in English 0=Zero: 1=One: 2=Two: 3=Three: 4=Four: 5=Five: 6=Six: 7=Seven: 8=Eight: 9=Nine: 10=Ten: # Default properties in German 0=Null: 1=Eins: 2=Zwei: 3=Drei: 4=Vier: 5=Fünf: 6=Sechs: 7=Sieben: 8=Acht: 9=Neun: 10=Zehn: # Default properties in French 0=Z: 1=Uun: 2=deux: 3=Trois: 4=Quatre: 5=cinq: 6=Six: 7=Sept: 8=Huit: 9=Neuf: 10=Dix: random=au
  • 63. <key>=<value> in a property file having new line char as separator. Message.prop HELLO_MESSAGE= Hello, How r u ? Message_ge.prop HELLO_MESSAGE= Hallo, Wie geht es Ihnen?? Message_sp.prop HELLO_MESSAGE= Hola, ¿Cómoestás?
  • 64. How to find out the user’s lang. preference. 2 ways allow the user to choose language. Get it as request parameter. It can use locale preferences that are sent from the client to the server using HTTP request header field Accept-Language. Use getLocale() . Implementation in application : Approach 1 Provide a version of JSPs page in each of the target locales and have the controller servlet dispatch the request to appropriate page. Choose when large amount data is available on page. Diadvantage is to create jsp pages for each locale.
  • 65. Approach 2 Isolate the locale sensitive data on a page into resource bundles. (error message, labels, button values etc..) Can be automatically retrieved from property file display in jsp. Choose when less content. Generally used. example.jsp <%@page import=“java.util.*”%> <% ResourceBundle rb= (ResourceBundle) request.getAttribute(“resourse”); %> <%= rb.getString(“HELLO_MESSAGE”) %>
  • 66. Public class I18NServlet extends HttpServlet { Public void service( req, response) throws SE, IO { String cc=req,getParameter(“country”) ; String lang=req,getParameter(“language”) ; Locale l=null; if(cc==null) l=new Locale(ln); else l=new Locale(ln,cc); ResourceBundle rb= ResourceBundle.getBundle(“AppsResourse”,l); req.setAttribute(“resource”,rb); req.getRequestDispatcher(“example.jsp”).forward(req,res); } }

Notes de l'éditeur

  1. * For entire web Apps
  2. ServletRequestEventEvents are getServletRequest () and getServletContext() ServletRequestEvent is child class of java.util.EventObject
  3. If u want to compress some response then we have to implement servletResponse interface and override all the methods , but we need only one or two … so java provides 4 wrapper classes,……..
  4. &lt;key&gt;=&lt;value&gt; in a property file having new line char as separator….HELLO_MESSAGE= Hello, How r u ?HELLO_MESSAGE= Hallo, Wie geht es Ihnen??HELLO_MESSAGE= Hola, ¿Cómoestás?