We will get the configuration information detail from the web.xml file by using FilterConfig object which is created by the web container.
There are following 4 methods in the FilterConfig interface.
In this example, if you change the param-value to no, request will be forwarded to the servlet otherwise filter will create the response with the message: this page is underprocessing. Let's see the simple example of FilterConfig.
<html> <body> <a href="Myservlet">click</a> </body> </html>
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; public class MyFilter1 implements Filter{ FilterConfig config; public void init(FilterConfig config) throws ServletException { this.config=config; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { PrintWriter out=resp.getWriter(); String s1=config.getInitParameter("processing"); if(s1.equals("yes")){ out.print("This page is under processing"); } else{ chain.doFilter(req, resp);//sends request to next resource } } public void destroy() {} }
import java.io.IOException; import java.io.PrintWriter; impor javax.servlet.ServletException; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("welcome to JavaRace"); } }
<web-app> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> <filter> <filter-name>f1</filter-name> <filter-class>MyFilter</filter-class> <init-param> <param-name>processing</param-name> <param-value>no</param-value> </init-param> </filter> <filter-mapping> <filter-name>f1</filter-name> <url-pattern>/WelcomeServlet</url-pattern> </filter-mapping> </web-app>
Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.
We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc