Monday, August 20, 2012

Can we override Dispatcher Servlet?

Yes. We can extends Dispatcher servlet if we want any special functionality during initialization.
If we want to display Bean names in Web Application  Context




package com.suresh.dispatcher;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;

import org.springframework.beans.BeansException;
import org.springframework.web.context.WebApplicationContext;
public class DispatcherServlet extends org.springframework.web.servlet.DispatcherServlet {

    /**
     *
     */
    private static final long serialVersionUID = 1L;
   
    @Override
    public void init(ServletConfig config) throws ServletException {
        // TODO Auto-generated method stub
        System.out.println("In suresh dispatcher servlet init method");
        super.init(config);
    }
   
    @Override
    protected WebApplicationContext initWebApplicationContext()
            throws BeansException {
        // TODO Auto-generated method stub
        System.out.println("In suresh dispatcher servlet WebApplicationContext method");
   
        WebApplicationContext wac = super.initWebApplicationContext();
        if(null!=wac){
        System.out.println("WAC Display Name " + wac.getDisplayName());
        String[] beanNames = wac.getBeanDefinitionNames();
        for(String bean:beanNames){
        System.out.println(" bean names " + bean) ;
        }
        }else{
           
            System.out.println("Web Application context is null ") ;
        }
        return wac;
    }

Web.exml


<servlet>
<servlet-name>dispatcherServlet</servlet-name>
  <servlet-class>com.suresh.dispatcher.DispatcherServlet</servlet-class>
  <load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


1 comment: