Servlet Filter is a unique concept of java technology, which intercept to Http repuest in web application. It's can intercept Http request for servlets, JSP's or other static contents.
Filter's, In which servlet filter's doesn't dependent on each other that means Sevrlet filter's are working independent.
Usage of Servlet Filter
Tracking and recording to all incoming http requests.
Data compression.
Encryption and decryption.
Validate input data .
Following example will help to batter understand servlet filter :
Create index.html and put below html code
<a href="servletFilter">click here</a>
Create servlet filter as MyFilter.java and put below code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {}
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
PrintWriter out=resp.getWriter();
out.print("filter is call before");
chain.doFilter(req, resp);//sends request to next resource
out.print("filter is call after");
}
public void destroy() {}
}
Create servlet as ServletFilter.java and put below code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class ServletFilter 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 Bhagwan Singh<br>");
}
}
Create web.xml for define the servlet filter and there filter element of web-app must be defined just like servlet.
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>ServletFilter</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servletFilter</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servletFilter</url-pattern>
</filter-mapping>
</web-app>
0 Comment(s)