Olá. Estou com o erro de NullPointerException mesmo tratando um cookie null.
Erro:
HTTP Status 500 -
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
br.com.alura.gerenciador.Filtro.doFilter(Filtro.java:31)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.79 logs.
Apache Tomcat/7.0.79
Minha classe:
package br.com.alura.gerenciador;
import java.io.IOException;
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.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
@WebFilter(urlPatterns="/*")
public class Filtro implements Filter{
@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;
Cookie cookie = getUsuario(request);
System.out.println("Usuário acessando a página: " + request.getRequestURI());
System.out.println("Cookie:" + cookie.getName());
chain.doFilter(req, resp);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
// TODO Auto-generated method stub
}
public Cookie getUsuario(HttpServletRequest req){
Cookie[] cookies = req.getCookies();
if (cookies == null){
return null;
}
for (Cookie cookie : cookies) {
if (cookie.getName().equals("usuario.logado")) {
return cookie;
}
}
return null;
}
}