HI,
Can anyone give me the idea for why we use Filter in web applicaiton. eg in servlet.
Thanks
Noorul.
Printable View
HI,
Can anyone give me the idea for why we use Filter in web applicaiton. eg in servlet.
Thanks
Noorul.
Hi ,
Filters are acts as a front end design pattern. It mean any request go through to filter. These filters are used for authentication purpose, to store loggin informations, data compression and image conversion etc. For example given filter check given request get or post.
public class AutFilter implements Filter {
public void init(FilterConfig config) {
System.out.println("init method called");
}
public void doFilter(ServletRequest request,ServletResponse respons,FilterChain chain) throws IOException {
HttpServletRequest hrequest=(HttpServletRequest)request;
PrintWriter out=request.getWriter();
if(hrequest.getMethod().equalsIgnoreCase("post")) {
chain.doFilter(request,response);
}
else {
out.write("get method is not allowed");
}
}
public void destroy() {
System.out.println("destroy method is called");
}
}
in web.xml:
<web-app>
<filter>
<filter-name>AutFilter</filtr-name>
<filter-class>AutFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AutFilter</filtr-name>
<url-pattern>/*</url-patterm>
</filter-mapping>
</web-app>
one.html:
-----------
<head> <body> <form action="/webproject/two.html" method="post"> <inpu type="submit" vaue="submit: /></form></body></html>
two.html:
-----------
it is two.html.
For filters no need to used <load-on-startup> tag.Defaultly the server create the object for filters at deployment time and it call the init(FilterConfig) method. Every filter conatin the url-pattern /* , hence whenever send the request to server (/webproject/one.html) , the server call the doFilter(-,-,-) of the AutFilter. This method check given request is get or post. If it is post request the doFilter(request,response) method send request to two.html .If it is get request just it display the "get method is not allowed".
Filters are powerful features provided by servlet API to implement cross-cutting features such as logging, auditing, keeping track of user activities, zipping a large file before sending it to a user, or creating a different response altogether.