We can carry out authentication in filter. Here, we're going to test the password given through the consumer in filter class. If the given password is admin, it'll forward the request to the WelcomeAdmin servlet. In any other case it's going to show a mistake message.
Let's see the easy instance of authenticating a person using a filter.
Here, we've created four files:
Index.html
<form action="servlet1"> Name:<input type="text" name="name"/><br/> Password:<input type="password" name="password"/><br/> <input type="submit" value="login"> </form>
Myfilter.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.*; public class MyFilter implements Filter{ public void init(FilterConfig arg0) throws ServletException {} public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { PrintWriter out=resp.getWriter(); String password=req.getParameter("password"); if(password.equals("admin")){ chain.doFilter(req, resp);//sends request to next resource } else{ out.print("username or password error!"); RequestDispatcher rd=req.getRequestDispatcher("index.html"); rd.include(req, resp); } } public void destroy() {} }
AdminServlet.java
import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.*; public class AdminServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print("welcome ADMIN"); out.close(); } }
Web.xml
<web-app> <servlet> <servlet-name>AdminServlet</servlet-name> <servlet-class>AdminServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>AdminServlet</servlet-name> <url-pattern>/servlet1</url-pattern> </servlet-mapping> <filter> <filter-name>f1</filter-name> <filter-class>MyFilter</filter-class> </filter> <filter-mapping> <filter-name>f1</filter-name> <url-pattern>/servlet1</url-pattern> </filter-mapping> </web-app>
download this example (developed using Myeclipse IDE)