Wednesday, 30 September 2015

Authentication Filter

Authentication Filter

We can perform authentication in filter. Here, we are going to check to password given by the user in filter class, if given password is admin, it will forward the request to the WelcomeAdmin servlet otherwise it will display error message.

Example of authenticating user using filter

Let's see the simple example of authenticating user using filter.
Here, we have created 4 files:
  • index.html
  • MyFilter.java
  • AdminServlet.java
  • web.xml
index.html
  1. <form action="servlet1">  
  2. Name:<input type="text" name="name"/><br/>  
  3. Password:<input type="password" name="password"/><br/>  
  4.   
  5. <input type="submit" value="login">  
  6.   
  7. </form>  

MyFilter.java
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3. import javax.servlet.*;  
  4.   
  5. public class MyFilter implements Filter{  
  6.   
  7. public void init(FilterConfig arg0) throws ServletException {}  
  8.       
  9. public void doFilter(ServletRequest req, ServletResponse resp,  
  10.         FilterChain chain) throws IOException, ServletException {  
  11.           
  12.     PrintWriter out=resp.getWriter();  
  13.           
  14.     String password=req.getParameter("password");  
  15.     if(password.equals("admin")){  
  16.     chain.doFilter(req, resp);//sends request to next resource  
  17.     }  
  18.     else{  
  19.     out.print("username or password error!");  
  20.     RequestDispatcher rd=req.getRequestDispatcher("index.html");  
  21.     rd.include(req, resp);  
  22.     }  
  23.           
  24. }  
  25.     public void destroy() {}  
  26.   
  27. }  

AdminServlet.java
  1. import java.io.IOException;  
  2. import java.io.PrintWriter;  
  3.   
  4. import javax.servlet.ServletException;  
  5. import javax.servlet.http.*;  
  6.   
  7. public class AdminServlet extends HttpServlet {  
  8. public void doGet(HttpServletRequest request, HttpServletResponse response)  
  9.         throws ServletException, IOException {  
  10.   
  11.         response.setContentType("text/html");  
  12.         PrintWriter out = response.getWriter();  
  13.           
  14.         out.print("welcome ADMIN");  
  15.         out.close();  
  16.     }  
  17. }  

web.xml
  1. <web-app>  
  2.  <servlet>  
  3.     <servlet-name>AdminServlet</servlet-name>  
  4.     <servlet-class>AdminServlet</servlet-class>  
  5.   </servlet>  
  6.   
  7.   <servlet-mapping>  
  8.     <servlet-name>AdminServlet</servlet-name>  
  9.     <url-pattern>/servlet1</url-pattern>  
  10.   </servlet-mapping>  
  11.     
  12.  <filter>  
  13.   <filter-name>f1</filter-name>  
  14.   <filter-class>MyFilter</filter-class>  
  15.   </filter>  
  16.   <filter-mapping>  
  17.   <filter-name>f1</filter-name>  
  18.   <url-pattern>/servlet1</url-pattern>  
  19.   </filter-mapping>  
  20.     
  21. </web-app>  

No comments:

Post a Comment