Example for API Filter in Servlet.
index.html
[html]
<html>
<form action="./welcome">
username:<input type = "text" name = "userName"/></br></br>
<input type = "submit" value="Login to SPlessons"/>
</form>
</html>
[/html]
web.xml
[xml]
<web-app>
<servlet>
<servlet-name>servlet</servlet-name>
<servlet-class>servletfilter.DemoServletFilters</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<filter>
<filter-name>filter</filter-name>
<filter-class>servletfilter.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>filter</filter-name>
<url-pattern>/welcome</url-pattern>
</filter-mapping>
</web-app>
[/xml]
Following is the
web.xml pattern when using filters.
MyFilter.java
[java]
package servletfilter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
public class MyFilter implements Filter{
public void init(FilterConfig arg0) throws ServletException {
//initialization of filter
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
PrintWriter out=response.getWriter();
String userName = request.getParameter("userName");
out.print("<h2>Hello "+userName+"</h2>");
chain.doFilter(request, response);//sends request to next resource
out.print("<h2>Thank you "+userName+"</h2>");
}
public void destroy() {
//servlet filter destroy
}
}
[/java]
API Filter in Servlet -
public void init(FilterConfig config) is invoked only once it is used to initialize the filter. The
doFilter technique for the Filter is called by the container every time a request/response pair is gone through the chain because of a client request for an asset toward the end of the chain. All filters are chained (in the order of their definition in web.xml). The
chain.doFilter() is proceeding to the next element in the chain. The last element of the chain is the target resource/servlet. The
public void destroy() is invoked only once when filter is taken out of the service.
DemoServletFilters.java
[java]
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class DemoServletFilters extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("
<h2>welcome to Splessons ServletFilters</h2>
");
}
}
[/java]
Output
By compiling the code one can get the following output as shown below, enter the username and add button.
By clicking on the button following message will be displayed.