Faced such a problem. In the database, I recorded a class object Cookie like this:

public void addUser(String telephone , String name , Cookie cookie) { try { String query = "INSERT INTO users (idTelephone , Name , cookie) VALUES ('"+telephone+"','"+name+"', ?);"; System.out.println(query); prepare = connect.prepareStatement(query); prepare.setObject(1, cookie); prepare.executeUpdate(); prepare.close(); }catch(SQLException ex) { ex.printStackTrace(); } } 

I read this way:

 public Cookie enter(String telephone , String name) { Cookie cookie = null; try { String query = "SELECT Cookie FROM users WHERE idTelephone ='"+telephone+"' "+" AND Name = '"+name+"';"; stat = connect.createStatement(); result = stat.executeQuery(query); result.next(); cookie = (Cookie) result.getObject("Cookie"); stat.close(); }catch(SQLException ex) { ex.printStackTrace(); } return cookie; } 

This is where I accept cookies:

 ModelFiles model = new ModelFiles((Connection) getServletContext().getAttribute("Connection")); Cookie cookie = model.enter(telephone , name); if(cookie != null) { response.addCookie((Cookie)cookie); response.sendRedirect("Load.jsp"); } else { response.sendRedirect("FailAuthorization.html"); } } 

Knocks out such an error:

[B cannot be cast to javax.servlet.http.Cookie at Models.ModelFiles.enter (ModelFiles.java:145)

Cookie = (Cookie) result.getObject ("Cookie");

Tried to check on instofof before attempting to lead to Cookie

 if(cookie instanceof Cookie){ system.out.println("Кастится") }else{ system.out.println("Не кастится"); 

Result:

It does not cast (that is, it is not given);

In the database I store the cookie in the column type Blob here:

enter image description here

In OBD OBJECT RECORDED! Just back I just can not pick up)

  • I tried to do this: take instead of the Object Blob. getBlob () and casting it - nothing happens - Sckoriy

1 answer 1

  public Cookie enter(String telephone , String name) { Cookie cookie = null; try { String query = "SELECT Cookie FROM users WHERE idTelephone ='"+telephone+"' "+" AND Name = '"+name+"';"; stat = connect.createStatement(); result = stat.executeQuery(query); result.next(); InputStream in = result.getBinaryStream("Cookie"); ObjectInputStream ois = new ObjectInputStream(in); cookie = (Cookie)ois.readObject(); stat.close(); }catch(SQLException ex) { ex.printStackTrace(); }catch(IOException ex) { ex.printStackTrace(); }catch(ClassNotFoundException ex) { ex.printStackTrace(); } return cookie; } 

I’m lying like this, trying to fall asleep, and remembered the deserialization of objects! The setObject method writes a serialized object. And I need to read a disrialized object! Then I can bring Object to Cookie!