Step 9: Filters

Filter is used for pre-processing of requests and post-processing of responses.

Filter Api- it’s a part of servlet api, filter interface can be found in javax.servlet package.

Life cycle-
1- init
2- dofilter
3- destroy

Filterchain interface- its used to invoke other filters in the chain.

Example 11- Web app to show pre-processing text before request is handled by servlet and post-processing text after response is generated by servlet.

output-

zxc

Project Structure-

mlp

3 files-

1-index.html(inside WebContent)

2-Firstfil.java(inside pacage=’ab’)

3-FirstServ.java(inside pacage=’ab’)

4-SecFil.java(inside pacage=’ab’)

5-web.xml(inside WEB-INF)

1-index.html






Insert title here









2-Firstfil.java(filter)


package ab;

import java.io.*;
import javax.servlet.*;

public class Firstfil implements Filter {

public void destroy() {
// TODO Auto-generated method stub
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String fs=request.getParameter("name");
System.out.println("first filter "+fs);
chain.doFilter(request, response);
System.out.println("after first filter chain-dofilter");
}
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}

}

3-FirstServ.java(servlet)


package ab;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServ extends HttpServlet {
private static final long serialVersionUID = 1L;

public FirstServ() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

String fs=request.getParameter("name");
response.getWriter().print(fs);
System.out.println("first servlet "+fs);
// pass the request along the filter chain
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}

}

4-SecFil.java(filter)


package ab;

import java.io.*;
import javax.servlet.*;

public class SecFil implements Filter {

public void destroy() {
// TODO Auto-generated method stub
}

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
String fs=request.getParameter("name");
System.out.println("second filter "+fs);
// pass the request along the filter chain
chain.doFilter(request, response);
System.out.println("after second filter chain-dofilter");
}

public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}

}

5-web.xml




Filters

index.html
index.htm
index.jsp
default.html
default.htm
default.jsp


a
ab.Firstfil


a
/FirstServ



b
ab.FirstServ


b
/FirstServ



c
ab.SecFil


c
/FirstServ



Advertisements