❮ Previous Next ❯

Authentication Filter

In Filter, we can perform authentication also. Let’s see the following example, here, we are

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>

 

❮ Previous Next ❯

Follow Us





  Tutorials

Popular Links

Contact Us

address Plot No-741,2ND Floor
Opp. Bhagabati Temple,Jayadev Vihar
      Bhubaneswar-751013
      Email: info@silantechnology.com
      Phone: 0674-2361252
address
39877, sundale dr, apt#101, Fremont, California 94538, USA
       Phone: +1(262)388-7619

facebook twitter google linked in

© 2018 Silan Technology. All Rights Reserved