会话过滤器上的NPE

时间:2013-08-20 05:18:06

标签: java jsp tomcat

我正在尝试检查过滤器中某些页面上的Cookie。我的代码如下:

public class SessionFilter implements Filter {

 private ArrayList<String> urlList;

@Override
public void destroy() {
// TODO Auto-generated method stub

}

@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
  throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String url = request.getServletPath();
boolean allowedRequest = false;

if (urlList.contains(url)) {
  allowedRequest = true;
}

String username = null;
String password = null;
String loggedin = null;

if (!allowedRequest) {
  Cookie[] cookies = request.getCookies();

  for (int i = 0; i < cookies.length; i++) {
    String name = cookies[i].getName();
    String value = cookies[i].getValue();

    if (name.equals("bccn_username"))
      username = value;
    else if (name.equals("bccn_password"))
      password = value;
    else if (name.equals("bccn_loggedin"))
      loggedin = value;
  }

  if (loggedin.equals("true")) {
    if (username != null && password != null) {
      CheckLogin obj = new CheckLogin();
      String ret = obj.check(username, password);
      if (ret.equals("Logged In")) {

      } else {
        response.sendRedirect("login.jsp");
      }
    } else {
      response.sendRedirect("login.jsp");
    }
  } else {
    response.sendRedirect("login.jsp");
  }

} else {
  response.sendRedirect("login.jsp");
}

chain.doFilter(req, resp);

}

@Override
public void init(FilterConfig config) throws ServletException {
String urls = config.getInitParameter("avoid-urls");
StringTokenizer token = new StringTokenizer(urls, ",");

urlList = new ArrayList<String>();

while (token.hasMoreTokens()) {
  urlList.add(token.nextToken());

}

}

}

在web.xml中

  <filter>
<filter-name>SessionFilter</filter-name>
<filter-class>
    ws.abhis.SessionFilter
</filter-class>
<init-param>
    <param-name>avoid-urls</param-name>
    <param-value>index.html</param-value>
    <param-value>login.jsp</param-value>
    <param-value>styles.css</param-value>
</init-param>
</filter>
<filter-mapping>
  <filter-name>SessionFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping>

但是,我在应用程序加载时收到此错误:

java.lang.NullPointerException
    ws.abhis.SessionFilter.doFilter(Unknown Source)

我是一个菜鸟,所以任何帮助都表示赞赏。

TIA。

1 个答案:

答案 0 :(得分:0)

您的urlList变量似乎未初始化并对其执行操作,如下所示:

if (urlList.contains(url)) 

将导致空指针异常。

确保在使用之前初始化列表。