Method | Description |
---|---|
public void init(FilterConfig, filterConfig) | Invoked by the web container to specify a filter that it is placed into service. |
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) | Called by the web container each time. The FilterChain is used to invoke the next filter in the chain. |
public void destroy( ) | It is called by the web container to specify that the servlet class is taken out of the service. |
//welcome.html
<form method="post" action="test">
Username:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="submit" />
</form>
//web.xml
<web-app>
<filter>
<filter-name>TestFilter</filter-name>
<filter-class>TestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>TestFilter</filter-name>
<servlet-name>test</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
</web-app>
//TestFilter.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class TestFilter implements Filter
{
public void init(FilterConfig fc) throws ServletException {}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException
{
PrintWriter out = response.getWriter();
String pass = request.getParameter("pass");
if(pass.equals("123456"))
{
chain.doFilter(request, response);
}
else
{
out.println("Password does not match");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
public void destroy()
{
}
}
//test.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class test extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
out.println("Welcome "+user);
}
}