Authentication Filter

In Filter, we can perform authentication als

checking password given by the user in filter class, if given password is ABC, it will

forward the request to the Welcome servlet otherwise it will display error message.
Example of authentication using filter

Required Files:

  1. index.html
  2. MyFilter1.java
  3. WelcomeServlet.java
  4. web.xml

index.html
<form action="WelcomeServlet">  
Name:<input type="text" name="name"><br/>  
Password:<input type="password" name="pwd"><br/>  
  
<input type="submit" value="login">  
  
</form>  

MyFilter1.java
import java.io.IOException;  
import java.io.PrintWriter;  
import javax.servlet.*;  
  
public class MyFilter1 implements Filter{  
  
public void init(FilterConfig arg0) throws ServletException {}  
      
public void doFilter(ServletRequest request, ServletResponse response,  
        FilterChain chain) throws IOException, ServletException {  
          
    PrintWriter out=response.getWriter();  
          
    String s =request.getParameter("pwd");  
    if(s.equals("ABC")){  
    chain.doFilter(request, response);//sends request to next resource  
    }  
    else{  
    out.print("Invalid username or password");  
    RequestDispatcher rd=request.getRequestDispatcher("index.html");  
    rd.include(request, response);  
    }  
          
}  
    public void destroy() {}  
  

 

WelcomeServlet.java
import java.io.IOException;  
import java.io.PrintWriter;  
  
import javax.servlet.ServletException;  
import javax.servlet.http.*;  
  
public class WelcomeServlet extends HttpServlet {  
public void doGet(HttpServletRequest request, HttpServletResponse response)  
        throws ServletException, IOException {  
  
        response.setContentType("text/html");  
        PrintWriter out = response.getWriter();  
          
        out.print("welcome JavaRace");  
        out.close();  
    }  
}  

 

web.xml
<web-app>  
 <servlet>  
    <servlet-name>WelcomeServlet</servlet-name>  
    <servlet-class>WelcomeServlet</servlet-class>  
  </servlet>  
  
  <servlet-mapping>  
    <servlet-name>WelcomeServlet</servlet-name>  
    <url-pattern>/WelcomeServlet</url-pattern>  
  </servlet-mapping>  
    
 <filter>  
  <filter-name>f1</filter-name>  
  <filter-class>MyFilter1</filter-class>  
  </filter>  
  <filter-mapping>  
  <filter-name>f1</filter-name>  
  <url-pattern>/WelcomeServlet</url-pattern>  
  </filter-mapping>  
    </web-app>

Our Services:

Java Training | Python Training | Machine Learning with Python Training | Deep Learning with Python Training | Projects

SILAN Technology
Call to: 9439202111  |  9658317757  |  0674-2361252

Comment