Solved

how to set a cookie and return an image in the same request

Posted on 2003-10-31
20
4,054 Views
Last Modified: 2010-04-01
I have a landing page on another domain - i.e. www.domain1.com

in a page on that domain - there is the following:

<img src="http://www.domain2.com/g1.jsp">

(an image src that points to a jsp on another domain.)
 What the g1.jsp is supposed to do is to set the cookie on the client's machine and then redirect to a blank.gif image. The problem is that I cannot set a cookie on the client's machine and return an image without 1) doing something with the content header i believe. or 2) breaking up into two steps because a cookie is added to the reponse object and there can only be one response for each request.
0
Comment
Question by:rbrett2003
  • 8
  • 5
  • 5
  • +2
20 Comments
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
two options come to my mind:

option 1: (I didn't try this one myself, so cannot be 100% sure if it will work)
in the jsp page, you added to cookie to the response and then use response.sendRedirect() to the blank.gif image.

option 2: (I'm 100% sure it will work)
for this option to work. you must use serlvet, if you must use g1.jsp, then let it simply forward to the servlet. the idea is let the servlet set the cookie and then read the blank.gif file from file system and return it back as the content. I'm gettiing you a sample servlet code, you can easily customized for your need.

let me know if you have further enquires.
0
 

Author Comment

by:rbrett2003
Comment Utility
i think i did this in principle but it didn't seem to work. If you have a simplified example, that would help.
0
 
LVL 19

Expert Comment

by:cheekycj
Comment Utility
can you post your code?

CJ
0
 
LVL 19

Expert Comment

by:cheekycj
Comment Utility
I have done this before (in a servlet)

CJ
0
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
sample code:

CookieImage.java
======================
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class CookieImage extends HttpServlet {

     public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
     {
           InputStream in = null;
           OutputStream out = null;
           try {
                // use one of those below.
                // in = getServletContext().getResourceAsStream("/resource/path/to/image/file");
                in = new FileInputStream( "/path/to/image/file" );
                if( in != null ) {
                    out = new BufferedOutputStream( response.getOutputStream() );
                    in = new BufferedInputStream( in );
                    response.setContentType( "image/gif" );
                    int c; while( ( c=in.read() ) != -1 ) out.write( c );
                    return;
                }
           } finally {
                if( in != null ) try { in.close(); } catch( Exception e ) {}
                if( out != null ) try { out.close(); } catch( Exception e ) {}
           }
     }
}
0
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
forgot to mention that you need to add cookie somewhere before response.getOutputStream() call.
0
 

Author Comment

by:rbrett2003
Comment Utility
I was doing the following:

in g1.jsp:

<%
  System.out.println("setting cookie");
Cookie cookie1 = new Cookie("abc", "confirm123");
  cookie1.setMaxAge(24 * 60 * 60);
  response.addCookie(cookie1);

  response.sendRedirect("blank.gif");
%>

when it returns, it returns the image, but didn't set the cookie.
Where in the above code do you set the cookie?

0
 
LVL 19

Expert Comment

by:cheekycj
Comment Utility
you don't want to use a redirect when you set a cookie.  the cookie will not get set.

use kennethxu's code and add the cookie code in it like so:

CookieImage.java
======================
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public final class CookieImage extends HttpServlet {

     public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, java.io.IOException
     {
           InputStream in = null;
           OutputStream out = null;
           try {
               Cookie cookie1 = new Cookie("abc", "confirm123");
               cookie1.setMaxAge(24 * 60 * 60);
               response.addCookie(cookie1);

                // use one of those below.
                // in = getServletContext().getResourceAsStream("/resource/path/to/image/file");
                in = new FileInputStream( "/path/to/image/file" );
                if( in != null ) {
                    out = new BufferedOutputStream( response.getOutputStream() );
                    in = new BufferedInputStream( in );
                    response.setContentType( "image/gif" );
                    int c; while( ( c=in.read() ) != -1 ) out.write( c );
                    return;
                }
           } finally {
                if( in != null ) try { in.close(); } catch( Exception e ) {}
                if( out != null ) try { out.close(); } catch( Exception e ) {}
           }
     }
}

Delete your g1.jsp
add a servlet url mapping your web.xml to map g1.jsp to the CookieImage Servlet

CJ
0
 

Author Comment

by:rbrett2003
Comment Utility
This doesn't work either. If I call CookieImage Servlet then it sets the cookie, but i cannot set the cookie this way:


if it's coming from the image src.

<html>
<head>
</head>
<body>
<img src="http://www.domain.com/path/to/CookieImage">
</body>
</html>

the servlet works fine, but it cannot seemed to be called from an image tag in a plain old html file.

0
 

Author Comment

by:rbrett2003
Comment Utility
As i said before the image returns fine in the servlet above - but it will not set the cookie.

e.g.


File1                                               ->                       cookieImage servlet

(contains img src tag)                                                 sets cookie returns image, (doesn't work)

user sees image.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 19

Expert Comment

by:cheekycj
Comment Utility
Map your servlet to a jsp in your web.xml

that will allow you to use.  I have done this before.  http://www.domain.com/path/to/CookieImage.jsp

in my web.xml on domain.com I map CookieImage.jsp to CookieImage Servlet.

CJ
0
 

Author Comment

by:rbrett2003
Comment Utility
I think you misunderstand me. The above code i compile as a servlet (CookieImage.java). What difference does it make if I make it a servlet or a jsp? so the img src goes directly to a servlet.
0
 
LVL 19

Expert Comment

by:cheekycj
Comment Utility
Your Servlet can return content type image/gif or image/jpeg and output an image without a redirect.

A JSP returns content type text/html so you cannot output an image , you have to use a redirect.  When you do a redirect you lose your cookie that was set.

CJ
0
 

Author Comment

by:rbrett2003
Comment Utility
But i'm not doing a redirect.

The html file with the image src calls the servlet directly -
<html>
<head>
</head>
<body>
<img src="http://www.domain.com/path/to/CookieImageServlet">
</body>
</html>

then, the CookieImageServlet sets the cookie and returns the image. Only the image returns, and the cookie isn't set. There is no jsp involved here. Am i missing something?
0
 
LVL 14

Expert Comment

by:kennethxu
Comment Utility
1. How do you example if the cookie is set? I mean how do you know it is not set?
2. Did you tried simple type the servlet url on browser's address bar? does it set cookie?

If you need to make your cookie available to other pages, you need to use cookie1.setPath("/");

Let us know.
0
 

Author Comment

by:rbrett2003
Comment Utility
Well, I look into the cache and I can see the cookie there. You can try this yourself :

go to:

http://rjbcomputers.dyndns.org:8080/examples/servlet/TestServlet

and you should see an image, then check your cache and you will see the cookie.

Now, create a web page whose img src points to that servlet and when you delete the cookie,
and then load up the web page, you will see that the cookie is not set.
0
 
LVL 14

Accepted Solution

by:
kennethxu earned 500 total points
Comment Utility
check the privacy setting of internet options, try set it to accept all cookies.
if you show the IE status bar, you'll see a Privacy Report icon when a cookies is rejected, double click to see the detail.
let us know.
0
 

Expert Comment

by:Farlander
Comment Utility
What was the resolution here ? I'm running into this same issue.

I've set up the sample servlet code from above. So, if I use IE, and open http://myserver/testservlet, image is returned and cookies are set. Now, make html page, with an image tag with src=http://myserver/testservlet, image comes back, but cookies are not set - at least, I can't see them under document.cookies in javascript.

Privacy settings are to allow all cookies - but nothing shows up. Any insight would be greatly appreciated.
0
 

Author Comment

by:rbrett2003
Comment Utility
the CookieImage.java seemed to work for me. Just needed to make sure that the browser wasn't caching the cookies.
0
 

Expert Comment

by:phil_powell
Comment Utility
Setting a cookie and redirecting is standard for page redirection in all scripting languages.  What you might consider doing is doing an HTTP page cache flush:

<meta http-equiv=Pragma content="no-cache">

Use the JSP-equivalent perhaps using response.setHeader() before you load HTML content and that will flush the cache before full page load and thus render your cookie.

Phil
0

Featured Post

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

Suggested Solutions

Marketing can be an uncomfortable undertaking, especially if your material is technology based. Luckily, we’ve compiled some simple and (relatively) painless tips to put an end to your trepidation and start your path to success.
Scam emails are a huge burden for many businesses. Spotting one is not always easy. Follow our tips to identify if an email you receive is a scam.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
Get a first impression of how PRTG looks and learn how it works.   This video is a short introduction to PRTG, as an initial overview or as a quick start for new PRTG users.

728 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

14 Experts available now in Live!

Get 1:1 Help Now