The Artima Developer Community
Sponsored Link

Legacy Java Answers Forum
October 2001

Advertisement

Advertisement

This page contains an archived post to the Java Answers Forum made prior to February 25, 2002. If you wish to participate in discussions, please visit the new Artima Forums.

Message:

Another work-around!

Posted by Jay on October 28, 2001 at 5:22 PM

After working on Rajeev Mutalik's question Invoking a servlet from core java program, I thought we might as well invoke servlet from the applet. So heres another solution:


1. Create a servlet which calls ResourceBuffer class


2. Call this servlet from the applet. (After the servlet is called, the servlet calls ResourceBuffer, which downloads the
image)


3. In the applet, make connection to the webserver and get this iamge.

Heres the code:

The ResourceBuffer class is the same as posted previously.

The servlet goes this way: (I am getting the URL of the image as a parameter)


import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;


public class MyServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException
{
PrintWriter out = response.getWriter();
ResourceBuffer rb = new ResourceBuffer();

String requestedURL = request.getParameter ( "imageLocation" );
System.out.println ( requestedURL );

if( rb.getResource( requestedURL ) )
{
System.out.println( "GOT IT!!" );
}
out.close();
}
}


Heres the applet code. The HTML file that contains the applet, when viewed with the browser, shows the image.

import java.applet.*;
import java.net.*;
import java.io.*;
import java.awt.image.*;
import java.awt.*;
public class ImageApplet extends Applet
{

private Image pic;

public void init()
{

String urlstring = "http://www.google.com/images/logo.gif";
if( urlstring != null )
{
try
{
String temp = "http://localhost/myservlet?imageLocation=" + urlstring;
System.out.println( temp );
URL url = new URL ( temp );
URLConnection connection = url.openConnection();
connection.setUseCaches (false);
connection.setDefaultUseCaches(false);

pic = getImage( new URL( "http://localhost/temp.gif" ) );
}
catch(Exception e)
{
System.out.println( e );
}
}
}
public void paint (Graphics g)
{
g.drawImage (pic, 0, 0, 400, 400, this);
}
}

Take care about the paths. ResourceBuffer class can not write file in the document root of the web server.





Replies:
  • hmm Chin Loong October 28, 2001 at 10:07 PM (0)

Sponsored Links



Google
  Web Artima.com   
Copyright © 1996-2009 Artima, Inc. All Rights Reserved. - Privacy Policy - Terms of Use - Advertise with Us