14.6.4 Write a filter example to read all the init parameters and display them on screen
Solution- Define a filter with two init params which filter will read and display. As in servlets, init parameter can be read through Servlet config object, similarly in filter we can read the init parameter through FilterConfig.
Servlet has a convenient method getServletConfig() available but in filter there is no such method available.
Filters provides FilterConfig object in initialization method so we can define a instance variable and map it to the one passed in init() method. Refer highlighted section in below code for more details.
- Add entry in web.xml
<filter> <filter-name>DisplayInitParamFilter</filter-name> <filter-class>com.servlet.tutorial.DisplayInitParamFilter</filter-class> <init-param> <param-name>param1</param-name> <param-value>value1</param-value> </init-param> <init-param> <param-name>param2</param-name> <param-value>Value2</param-value> </init-param> </filter> <filter-mapping> <filter-name>DisplayInitParamFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- Write Filter Code
package com.servlet.tutorial; import java.io.IOException; import java.io.PrintWriter; import java.util.Enumeration; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class DisplayInitParamFilter implements Filter { private FilterConfig filterConfig=null; @Override public void init(FilterConfig filterConfig) throws ServletException { System.out.println("Filter initialized..."); this.filterConfig = filterConfig; } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException { Enumeration<String> initParams= filterConfig.getInitParameterNames(); StringBuffer buffer = new StringBuffer(); while(initParams.hasMoreElements()) { String initParamName = initParams.nextElement(); String initParamValue =filterConfig.getInitParameter(initParamName); buffer.append(initParamName+"::" + initParamValue); } PrintWriter writer = response.getWriter(); writer.println(buffer.toString()); } @Override public void destroy() { System.out.println("Filter Destroyed.."); } }
Testing
Hit the url http://localhost:8080/HelloWorld/input.html and enter some value. In earlier example we created input.html so if we enter some value and submit it will pass the Interceptor filter and will execute the DisplayInitParamFilter