我正在尝试检查过滤器中某些页面上的 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。