Saturday, July 28, 2018

Example of FilterConfig

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 underconstruction.
  1. index.html
  2. MyFilter.java
  3. HelloServlet.java
  4. web.xml
index.html

<a href="servlet1">click here</a>

MyFilter.java

import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.*; 
 
public class MyFilter 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 s=config.getInitParameter("construction"); 
         
    if(s.equals("yes")){ 
         out.print("This page is under construction"); 
    } 
    else{ 
         chain.doFilter(req, resp);//sends request to next resource 
    } 
         

public void destroy() {} 
}   


HelloServlet.java

import java.io.IOException; 
import java.io.PrintWriter; 
 
import javax.servlet.ServletException; 
import javax.servlet.http.*; 
 
public class HelloServlet extends HttpServlet { 
public void doGet(HttpServletRequest request, HttpServletResponse response) 
        throws ServletException, IOException { 
 
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter(); 
     
        out.print("<br>welcome to servlet<br>"); 
         
    } 
 
}


web.xml

<web-app> 
 
 <servlet> 
    <servlet-name>HelloServlet</servlet-name> 
    <servlet-class>HelloServlet</servlet-class> 
  </servlet> 
 
  <servlet-mapping> 
    <servlet-name>HelloServlet</servlet-name> 
    <url-pattern>/servlet1</url-pattern> 
  </servlet-mapping> 
   
  <filter> 
  <filter-name>f1</filter-name> 
  <filter-class>MyFilter</filter-class> 
  <init-param> 
  <param-name>construction</param-name> 
  <param-value>no</param-value> 
  </init-param> 
  </filter> 
  <filter-mapping> 
  <filter-name>f1</filter-name> 
  <url-pattern>/servlet1</url-pattern> 
  </filter-mapping> 
   
   
</web-app>

No comments:

Post a Comment