Cookie problems with IE and Chrome (working with java)
I'm trying to send an image to the client from a servlet, and add a cookie containing the id of the image to the repsonse. ( i don't want to display the same image more than N times).
Looks like Internet Explorer doesn't care about the cookies and i always get a null reference when i call request.getCookies();. With Opera everything works great.
Chrome sees the cookies but i get the following exception when i write the image to the outputStream : ClientAbortException: java.net.SocketException: Software caused connection abort: socket write error
I haven't tried yet Mozilla.
Is there a workaround for Internet Explorer, except cookies? Sessions work with my Internet Explorer.
Any ideas for the exception raised when i use Chrome ? ( the image is less than 1 MB).
Here's the servlet code:
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("image/jpeg");
response.addHeader ("Content-Disposition", "attachment");
response.setHeader("Cache-Control", "no-cache,no-store,must-revalidate");
response.setHeader("Pragma", "no-cache");
response.setDateHeader("Expires", 0);
HttpSession session = request.getSession();
String requestURI = request.getParameter("requestURI");
String resolution = request.getParameter("resolution");
Cookie[] cookies = request.getCookies();
try
{
if (cookies == null)
coada = (new BannerChooser().Choose(1));
String filePath = null;
Iterator it = coada.iterator();
boolean found =false;
while ((!found) && it.hasNext())
{
found = true;
if (cookies!=null)
for (int i = 0; i < cookies.length; i++)
if ( Integer.parseInt(cookies[i].getValue()) == ((BannerNota)it.next()).getB().getId())
{
found = false;
开发者_Python百科 break;
}
if (found)
{
BannerNota bannerToDisplay = (BannerNota)it.next();
Cookie cookie = new Cookie(bannerToDisplay.getB().getId().toString(),bannerToDisplay.getB().getId().toString());
cookie.setMaxAge(60*60*24);
cookie.setPath("/licenta");
filePath = bannerToDisplay.getB().getPath();
response.addCookie(cookie);
break;
}
}
filePath = "h:/program files/Workspace/licenta/WebRoot/" + filePath;
File f = new File(filePath);
byte[] b = new byte[(int)f.length()];
FileInputStream fis = new FileInputStream(f);
fis.read(b);
ServletOutputStream out = response.getOutputStream();
out.write(b);
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
Cookies are domain based. Many browsers reject cookies on embedded resources (CSS/JS/images) which are served from other domain than the page is been served from.
You want to manage the cookie using JavaScript instead. Google Analytics is also doing it that way. At quirksmode.org you can find a nice tutorial how to manage cookies using JavaScript. Any cookie-based information can then be sent as a request parameter on the image URL.
精彩评论