authenticationfilter.java

来自「JAVA Servlet2.3外文书籍源码」· Java 代码 · 共 59 行

JAVA
59
字号
package forum;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.http.*;

/**
 * An implementation of a filter that checks whether a user has logged in
 * to the system and redirects them to the login.jsp page if they haven't.
 *
 * @author    Simon Brown
 */
public class AuthenticationFilter implements Filter {

  /** the filter configuation */
  private FilterConfig filterConfig;

  /**
   * Called when the filter is created/initialized.
   *
   * @param filterConfig    the FilterConfig instance
   */
  public void init(FilterConfig filterConfig) throws ServletException {
    this.filterConfig = filterConfig;
  }

  /**
   * Performs the functionality associated with this filter.
   *
   * @param request     the HttpServletRequest instance
   * @param response    the HttpServletResponse instance
   * @param chain       the complete chain of filters
   */
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest)req;
    HttpServletResponse response = (HttpServletResponse)res;

    // is the current user logged in?
    if (request.getSession().getAttribute("user") == null) {
      System.out.println("AuthenticationFilter : User is not logged in, redirecting them to /login.jsp");

      // no, so redirect them to the login page first
      RequestDispatcher dispatcher = filterConfig.getServletContext().getRequestDispatcher("/login.jsp");
      dispatcher.forward(request, response);
    } else {
      System.out.println("AuthenticationFilter : User is logged in");
      chain.doFilter(request, response);
    }
  }

  /**
   * Called when the filter is no longer being used.
   */
  public void destroy() {
  }

}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?