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

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.