0
package com.servlet.filter.UserAuthFilter ;

import java.io.IOException;
import java.util.ArrayList;
import java.util.StringTokenizer;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

// Implements Filter class
public class UserAuthFilter implements Filter {

  private ArrayList urlList;

  public void destroy() {
  }

  public void doFilter(ServletRequest req, ServletResponse res,
      FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;
    String url = request.getServletPath();
    boolean allowedRequest = false;
    String strURL = "";

    // To check if the url can be excluded or not
    for (int i = 0; i < urlList.size(); i++) {
      strURL = urlList.get(i).toString();
      if (url.startsWith(strURL)) {
        allowedRequest = true;
      }
    }

    if (!allowedRequest) {
      HttpSession session = request.getSession(false);
      if (session == null
          || session.getAttribute("session_uname") == null) {
        // Forward the control to login.jsp if authentication fails
        request.getRequestDispatcher("/login.jsp").forward(request,
            response);
      }
    }
    chain.doFilter(req, res);
  }

  public void init(FilterConfig config) throws ServletException {
    // Read the URLs to be avoided for authentication check (From web.xml)
    String urls = config.getInitParameter("avoid-urls");
    StringTokenizer token = new StringTokenizer(urls, ",");
    StrUrlList = new ArrayList();
    while (token.hasMoreTokens()) {
      StrUrlList.add(token.nextToken());
    }
  }
} 

Read More at
http://a4academics.com/blog/380-j2ee-user-authentication-using-java-servlet-filters

Edited by peter_budo: Moving to JSP

2
Contributors
1
Reply
2
Views
4 Years
Discussion Span
Last Post by peter_budo
0

There are multiple ways of doig, simple example you can find in MVC2 at the top of this forum section or you can have look on number of Java webframeworks Spring, Wicket etc

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.