Error logout cookie Servlet

Asked

Viewed 43 times

1

Hello. I have a line error:

Cookie cookie = new Cookies(req.getCookies().getUsuarioLogado();

The complete method/class is this:

@WebServlet(urlPatterns = "/logout")
public class Logout extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //String getCookies = req.getParameter(getCookies);
    //String getUsuarioLogado = req.getParameter(getUsuarioLogado);

    Cookie cookie = new Cookies(req.getCookies().getUsuarioLogado();
    if(cookie!=null) {
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }
    PrintWriter writer = resp.getWriter();
    writer.println("<html><body>Logout efetuado</body></html>");
    }
}

I am unable to solve the error. Does anyone know?

Thank you

2 answers

2

Hi! For you to generate a cookie is as follows:

Cookie cookie = new Cookie("nome_cookie", "valor_cookie");

The getCookies method returns the list of cookies. It does not have the getUsuarioLog method.

To retrieve the cookie you want, you must iterate the list returned by getCookies.

example:

Cookie[] cookies = req.getCookies();
for(Cookie cookie : cookies) {
  if(cookie.getName().equals("nome_que_você_deseja") {
     // faz o que você precisa
    break;
  }
}

I hope I’ve helped.

  • But I kind of want to know why you’re wrong about the line I mentioned.

  • 1

    @Thiagoferreira What was the error? You did not point. Type, I believe is the call attempt of the method: Cookie cookie = new Cookies(req.getCookies(). getUsuarioLog(); , not to mention that it is missing close the parentheses at the end of the line. But anyway you can’t do eq.getCookies(). getUsuarioLog() because getCookies returns an array of Cookies and not an object that has the getUsuarioLog method

  • this error: Cannot invoke getUsuarioLog() on the array type Cookie[]

  • closed the parentheses and continued the error.

  • 1

    So is as I said... you cannot do getUsuarioLog() because a Cookie[] does not have this method. The correct way is to do as I put in the answer, you have to iterate the Array and make your logic to recover the user.

  • I just put the parentheses in the right place and it worked right here.

Show 1 more comment

0


I managed to fix, my current code is like this:

public class Logout extends HttpServlet {

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    //String getCookies = req.getParameter(getCookies);
    //String getUsuarioLogado = req.getParameter(getUsuarioLogado);

    Cookie cookie = new Cookies(req.getCookies()).getUsuarioLogado();
    if(cookie!=null) {
        cookie.setMaxAge(0);
        resp.addCookie(cookie);
    }
    PrintWriter writer = resp.getWriter();
    writer.println("<html><body>Logout efetuado</body></html>");
}

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.