servlets - filter, listeners, wrapper, internationalization
DESCRIPTION
This presentation has introduction, advantages, and explanation of how to use these things. please read it give your suggestion....TRANSCRIPT
FILTERS, LISTENERS, WRAPPERS, INTERNATIONALIZATION.By,
Susnat sahu
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 Authentication, Logging, Authorization, Change request information , etc..
Post processing involves Compression of the response. Encryption of the response. To alter response information.
Other Tasks Security verification Session validation Internationalization Data compression MIME type changing
Advantages of Filters Encapsulate common behavior.
Have 30 different Servlet or JSP pages that need to compress their content to decrease download time? Make 1 compression filter and apply it to all 30 resources.
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.
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.
The Filter Life Cycle
Lets know about Filter APIThis API comprises of three interfaces
javax.servlet.Filter javax.servlet.FilterConfig javax.servlet.FilterChain
javax.servlet.Filter
Every Filter class must implement Filter interface either directly or indirectly.
void init(FilterConfig filterConfig)
Initializes a filter and makes it ready for providing service.
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 either
1. Throws a ServletException 2. Does not return within a time period defined by the web container
void doFilter (ServletRequest request, ServletResponse response, FilterChain chain)
Encapsulates service logic to be implemented on ServletRequest to generate the ServletResponse. The FilterChain refernce passed as an argument to forward request/response pair to the filter or target resource of chain.
void destroy( ) Called by the web container to indicate to a filter that it is being taken out of service.
javax.servlet.FilterConfigUsed 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.
Enumeration getInitParameterNames()
Returns the names of the filter's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the filter has no initialization parameters.
ServletContext getServletContext()
Returns a reference to the ServletContext in which the caller is executing.
javax.servlet.FilterChain 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 ?
1. Direct end-user request (REQUEST) (2.3 ver)2. By RequestDispatcher forward (FORWARD)3. By RequestDispatcher include (INCLUDE)4. By error page call (ERROR)
Java servlet 2.4 specification sun introduced <dispatcher> tag to extend filter concept for last 3 calls also.
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
REQUEST – This is default value. Filter will only execute only on end user request.
FORWARD - Filter will only execute for RequestDispatcher forward calls.
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 :
1.Request Listeners : ServletRequestListener ServletRequestAttributeListener
2.Context Listeners : ServletContextListener ServletContextAttributeListener
3. Session listeners : HttpSessionListener HttpSessionAttributeListener HttpSessionBindingListener HttpSessionActivationListener
ServletRequestListener :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)
ServletContextListenervoid contextInitialized(ServletContextEvent sce)
At the time of context object creation i.e. application deployment.
void contextDestroyed(ServletContextEvent sce)
At the time application un deployment.
ServletContextAttributeListener : void attributeAdded(ServletContextAttributeEventsrae) void attributeRemoved(ServletContextAttributeEvent
srae) void attributeReplaced(ServletRequestAttributeEvent
srae)
HttpSessionListener :
Related to life cycle of the session objects. void sessionCreated(HttpSessionEvent se) void sessionDestroyed(HttpSessionEvent
se)
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-INF\properties \log4j.properties
</param-value></init-param> <load-on-startup>1</load-on-startup> </servlet>
<listener> <listener-class>com.eias.logging.Log4jListener</listener-class></listener>
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.
ServletRequest ServletResponse HttpServletRequest HttpServletResponse
What are the core objects of servlet
API ?
ServletRequestWrapper This class implements ServletRequest interface, this class is further called by web developers to call
their overridden methods. This class implements the Wrapper or Decorator
pattern.
• getAttribute( ) The default behavior of this method is to call getAttribute(String name) on the wrapped request object.
• getRequest( )• getParameter( )• getParameterValues( )• setAttribute( ) • removeAttribute( )
ServletResponseWrapper This class implements ServletResponse interface getBufferSize()
Calls getBufferSize() response method on wrapped response object.
getResponse( ) getWriter( ) setContentType( ) setContentLength( )
Import javax.servlet.*;Public class MyRequestWrapper extends
ServletRequestWrapper{
Public MyRequestWrapper (ServletRequest req){Super(req); }
public String getParameter(String S) {String s1=super.getParameter(s);if(s1==null)
s1=“ NONE ”;return s1;}}
Import javax.servlet.*;Public class MyWrapperFilter implements Filter{ Public void init(FilterConfig fc) { } ;Public void destroy() { } ;
Public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws SE, IO … {
MyRequestWrapper wrapperReq= new MyRequestWrapper ();
Chian.doFilter(wrapperReq, res);
}
}
Wrapped request object
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
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..
Create a Locale object using the constructors in this class:
1. Locale(String language) 2. Locale(String language, String country)3. 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.
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.
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
Resource bundle name have two parts A base name A suffix that defines specific locale.
<base name>_<lang>_<country> . Properties
Numbersrb.properties - is the default Numbersrb_ge.properties Numbersrb_fr.properties
# Default properties in English0=Zero:1=One:2=Two:3=Three:4=Four:5=Five:6=Six:7=Seven:8=Eight:9=Nine:10=Ten:
# Default properties in German0=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 French0=Z:1=Uun:2=deux:3=Trois:4=Quatre:5=cinq:6=Six:7=Sept:8=Huit:9=Neuf:10=Dix:random=au
<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ómo estás?
How to find out the user’s lang. preference. 2 ways1. allow the user to choose language. Get it as request
parameter.
2. 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.
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”) %>
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);}}