Response Filter Servlet Example

This Example shows how to use of response filter in Java Servlet.
Filter reads
own initial parameters and adds its value to the response. Use the init-param child element of
the filter element to declare the initialization parameter and its value. Inside
the filter, access the init parameter by calling the FilterConfig object's
getInitParameter method.
Here is the source code of ResponseFilterExample.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ResponseFilterExample implements Filter{
private FilterConfig config = null;
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterchain)throws IOException, ServletException{
filterchain.doFilter(request, response);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<b>Filter Received Your Message Successfully:</b>" +
config.getInitParameter("response"));
}
public void destroy() { }
public void init(FilterConfig config) {
this.config = config;
}
}
|
The above code initialized the FilterConfig object in its init
methods, which is called once when the web container creates an instance of the
filter. The code then gets the value of the filter's init parameter by calling: config.getInitParameter("response").
Mapping for the filter in web.xml:
<filter>
<filter-name>ResponseFilterExample</filter-name>
<filter-class>ResponseFilterExample</filter-class>
<init-param>
<param-name>response</param-name>
<param-value>Hello Response Filter Example!</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ResponseFilterExample</filter-name>
<url-pattern>/JSP/response.jsp</url-pattern>
</filter-mapping> |
The source code of response.jsp:
<html>
<head>
<title>Response Filter Example</title>
</head>
<body>
<h2><font color="green">Response Filter and Initialized Parameters</font></h2>
<br>
</body>
</html> |
Running the program by this url: http://localhost:8080/JavaExample/JSP/response.jsp
the message will display below

Download Source Code

|