Wednesday, 19 February 2014

Why filter is used as Dispatcher or Controller?

In Struts FilterDispatcher is used as a common controller,As filters have also life cycle method similar to those of Servlets.

These are life cycle methods of a filter.
  •  init. Called once by the web container just before the filter is put into service.
  •  doFilter. Called by the web container each time it receives a request with a URL that matches the filter's URL Pattern
  • destroy. Called by the web container before the filter is taken out of service, i.e. when the application is shut down.
With a filter you can conveniently choose to serve all the resources in your application, including static ones. With a servlet, your controller only handles access to the dynamic part of the application.

Note that the url-pattern element in the web.xml file :
<servlet> 
<servlet-name>Controller</servlet-name> 
<servlet-class>...</servlet-class> 
</servlet>
 <servlet-mapping> 
<servlet-name>Controller</servlet-name>
 <url-pattern>*.action</url-pattern> 
</servlet-mapping>

With such a setting, requests for static resources are not handled by the servlet controller, but by the container. You wouldn't want to handle static resources in your servlet controller because that would mean extra work.

A filter is different. A filter can opt to let through requests for static contents. To pass on a request, call the filterChain.doFilter method in the filter's doFilter method.

Consequently, employing a filter as the controller allows you to block all requests to the application, including request for static contents. You will then have the following setting in your deployment descriptor:

 <filter> 
<filter-name>filterDispatcher</filter-name>
 <filter-class>...</filter-class> 
</filter> 
<filter-mapping>
 <filter-name>filterDispatcher</filter-name>
 <url-pattern>/*</url-pattern> 
</filter-mapping>

What is the advantage of being able to block static requests? One thing for sure, you can easily protect your static files from curious eyes.
 The following code will send an error message if a user tries to view a JavaScript file:

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
HttpServletRequest req = (HttpServletRequest) request; 
HttpServletResponse res = (HttpServletResponse) response; 
String uri = req.getRequestURI(); 
if (uri.indexOf("/css/") != -1 && req.getHeader("referer") == null) { res.sendError(HttpServletResponse.SC_FORBIDDEN);
 } 
else { // handle this request }}

It will not protect your code from the most determined people, but users can no longer type in the URL of your static file to view it. By the same token, you can protect your images so that no one can link to them at your expense.


Back to Struts home

No comments:

Post a Comment