Useful Filter Examples
There is given some useful examples of filter.
Example of sending response by filter only
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. public void init(FilterConfig arg0) throws ServletException {}
6.
7. public void doFilter(ServletRequest req, ServletResponse res,
8. FilterChain chain) throws IOException, ServletException {
9.
10. PrintWriter out=res.getWriter();
11.
12. out.print("<br/>this site is underconstruction..");
13. out.close();
14.
15. }
16. public void destroy() {}
17. }
Example of counting number of visitors for a
single page
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
6. public void init(FilterConfig arg0) throws ServletException {}
7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=res.getWriter();
12. chain.doFilter(request,response);
13.
14. out.print("<br/>Total visitors "+(++count));
15. out.close();
16.
17. }
18. public void destroy() {}
19. }
Example of checking total response time in
filter
MyFilter.java
1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class MyFilter implements Filter{
5. static int count=0;
6. public void init(FilterConfig arg0) throws ServletException {}
7.
8. public void doFilter(ServletRequest req, ServletResponse res,
9. FilterChain chain) throws IOException, ServletException {
10.
11. PrintWriter out=res.getWriter();
12. long before=System.currentTimeMillis();
13.
14. chain.doFilter(request,response);
15.
16. long after=System.currentTimeMillis();
17. out.print("<br/>Total response time "+(after-before)+" miliseconds");
18. out.close();
19.
20. }
21. public void destroy() {}
22. }
If this information is important to you , and you want to , I will continue writing some more details of programming language, so click on the advertising, available on this page. This is motivate me for writing some more blogs.
Comments
Post a Comment