Cheap VPS & Xen Server


Residential Proxy Network - Hourly & Monthly Packages

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. <input type=“submit” value=“login”>
  5. </form>

MyFilter.java

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

AdminServlet.java

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

web.xml

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

Comments

comments