Servlet Authentication Filter-

A filter is an object that is conjured at the preprocessing and postprocessing of a solicitation. Filters perform filtering in the doFilter method. Each Filter has entry to a FilterConfig object from which it can get its instatement parameters, a reference to the ServletContext which it can use, for instance, to load assets required for separating errands. The servlet filter is pluggable, i.e. its entrance is characterized in the web.xml document, in the event that we expel the section of channel from the web.xml record, channel will be uprooted naturally and we don't have to change the servlet.

Example

Let's see the simple example of authenticating user using filter.

Here, we have created 4 files:

  1. index.html
  2. MyFilter.java
  3. AdminServlet.java
  4. web.xml

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>