Solved

Java applet to servlet: is it really possible?

Posted on 2007-12-02
13
937 Views
Last Modified: 2013-11-24
I am wishing to connect to a servlet from within an applet and have scoured the net looking for examples.  I have located a few and have copied their code but it just doesn't work for me.  I am able to send data to the servlet but whenever I try to read from it I get this exception:

java.security.AccessControlException: access denied (java.util.PropertyPermission http.strictPostRedirect read)

Now, once again I have searched the net for this problem and it seems to have cropped up dozens of times.  Unfortunately I have gone though each one and I cannot find that any of them have been solved.  That leads me to wonder if I am trying to do something which simply isn't possible but then again why would other people be posting code that's supposed to work?

I have attached the code for the applet and the servlet both of which I downloaded from another site anyway.  Can anyone see why the applet fails?  I am really hoping it's a configuration issue on the server side.  BTW, signing the applet has been suggested as a possible solution to this problem on some sites but this is not appropriate in this context as it will be impossible to deliver this particular applet signed.

The environment is:

* Java 6 Update 3
* Firefox 2.0.0.11 browser
* Winstone 0.9.9 servlet container
* Both server and applet running on Windows Vista

Thanks very much,

KP
import java.applet.*;

import java.awt.*;

import java.io.*;

import java.net.*;
 

/**

 * Applet-Servlet communication example.<P>

 *

 * The Applet.  This applet allows you to type in a message, send it to a

 * servlet, and view what the servlet sends back.

 *

 * @author	James Farmer

 * @version	03-Aug-2000

 **/
 

public class EgApplet extends Applet {

  TextField servletUrlField;

  TextField messageField;

  TextArea responseField;

  Button transmitButton;
 

/**

 * This method just adds the components to the applet

 **/
 

  public void init() {

    super.init();

    this.setLayout(new BorderLayout());
 

    Panel topPanel = new Panel();

    topPanel.setLayout(new GridLayout(0,1));
 

    Panel servletUrlPanel = new Panel();

    servletUrlPanel.setLayout(new BorderLayout());

    servletUrlPanel.add("West", new Label("Servlet URL:", Label.RIGHT));

    servletUrlPanel.add("Center", servletUrlField = new TextField("http://mindy.cs.bham.ac.uk/servlets/appletServletExample.EgServlet"));

    topPanel.add(servletUrlPanel);
 

    Panel messageFieldPanel = new Panel();

    messageFieldPanel.setLayout(new BorderLayout());

    messageFieldPanel.add("West", new Label("Message to send:", Label.RIGHT));

    messageFieldPanel.add("Center", messageField = new TextField());

    topPanel.add(messageFieldPanel);
 

    this.add("North", topPanel);

    this.add("Center", responseField = new TextArea());

    responseField.setEditable(false);

    this.add("South", transmitButton = new Button("Transmit"));

  }
 
 
 

/**

 * Method to intercept clicks on the "transmit" button.  Note that we're using

 * the Java 1.0.2 event model here to ensure maximum compatibility with old

 * browsers.

 **/
 

  public boolean action(Event evt, Object obj) {

    if (obj.equals("Transmit")) {

      this.interactWithServlet();

      return true;

    }

    return false;

  }
 
 

/**

 * This method causes the applet to interact with the servlet.  Basically, the

 * method writes the message to the servlet, then reads the response and sticks

 * it in the "response" field.

 **/
 

  private void interactWithServlet() {

    try {
 

// Create an object we can use to communicate with the servlet

      URL servletURL = new URL(servletUrlField.getText());

      URLConnection servletConnection = servletURL.openConnection();

      servletConnection.setDoOutput(true);  // to allow us to write to the URL

      servletConnection.setUseCaches(false);  // to ensure that we do contact

                                              // the servlet and don't get

                                              // anything from the browser's

                                              // cache
 

// Write the message to the servlet

      PrintStream out = new PrintStream(servletConnection.getOutputStream());

      out.println(messageField.getText());

      out.close();
 

// Now read in the response

      InputStream in = servletConnection.getInputStream();

      StringBuffer response = new StringBuffer();

      int chr;

      while ((chr=in.read())!=-1) {

        response.append((char) chr);

      }

      in.close();

      responseField.setText(response.toString());
 
 

    } catch (IOException e) {

      e.printStackTrace();

      responseField.setText("An error occurred: " + e.toString());

    }

  }
 

}
 
 
 

import java.io.*;

import java.util.*;
 

import javax.servlet.*;

import javax.servlet.http.*;
 

/**

 * Applet-Servlet communication example.<P>

 *

 * The Servlet.  Basically, this reads in whatever's sent to it then sends

 * back an appropriate message.

 *

 * @author	James Farmer

 * @version	03-Aug-2000

 **/
 

public class EgServlet extends HttpServlet {
 
 

/**

 * Method to handle GET queries.

 **/
 

  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    resp.setContentType("text/plain");

    PrintWriter out = resp.getWriter();

    out.println("Error: this servlet does not support the GET method!");

    out.close();

  }
 
 

/** 

 * Method to handle POST queries.  It reads in from the input stream, then

 * writes out what it read along with a datestamp and some description.

 **/
 

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

// Read in the message from the servlet

    StringBuffer msgBuf = new StringBuffer();

    BufferedReader fromApplet = req.getReader();

    String line;

    while ((line=fromApplet.readLine())!=null) {

      if (msgBuf.length()>0) msgBuf.append('\n');

      msgBuf.append(line);

    }

    fromApplet.close();
 

// Write the message back to the applet

    resp.setContentType("text/plain");

    PrintWriter toApplet = resp.getWriter();

    toApplet.println("I (the servlet) received a message \"" + msgBuf.toString() + "\"");

    toApplet.println("at " + (new Date()).toString());

    toApplet.println("and sent this text in response.   Hope you enjoy it!");

    toApplet.close();

  }
 

}

Open in new window

0
Comment
Question by:KhaiPi
  • 7
  • 6
13 Comments
 
LVL 92

Expert Comment

by:objects
ID: 20393543
looks like your servlet is doing a redirect
0
 

Author Comment

by:KhaiPi
ID: 20393782
What does that mean exactly?  You can see in the servlet code that I am not doing anything in particular to do a redirect so why would one be happening?

KP
0
 
LVL 92

Expert Comment

by:objects
ID: 20393831
u sure thats the servlet you arre calling.
or some other server handling the request before passing it to servlet
Is the applet beoing served by winstone?
0
 

Author Comment

by:KhaiPi
ID: 20393849
> u sure thats the servlet you arre calling

Yes, it's the only server I have.

> or some other server handling the request before passing it to servlet

Not possible.

> Is the applet beoing served by winstone?

Yes, but I doubt that it's a Winstone issue per se given that the multitude of posts on similar matters all over the net refer to various application servers.  It's gotta be something to do with server configuration or a policy file but I am no expert in these areas.

KP
0
 

Author Comment

by:KhaiPi
ID: 20393859
I should add that I now know that it *can* work because if I run the applet from an external internet address (as provided by the applet/servlet author), it works and doesn't have any exceptions.  Same applet, different application server environment so it can't be a local security issue.
0
 
LVL 92

Expert Comment

by:objects
ID: 20393871
i know it can work too, and its not a local security issue
what url is the applet loaded with
and what url are you posting from applet?
0
Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

 

Author Comment

by:KhaiPi
ID: 20393888
I simply use this URL:

http://localhost:8080/index.html

Oh, I am glad you asked the next question as the source I have just realised that the source listed is not exactly what I am using.  I have substitued line 78 for:

URL servletURL = new URL(getCodeBase(), "eg");

so I am bypassing the entry of a URL altogether.  Sorry about that.

Does this make a difference?
0
 
LVL 92

Expert Comment

by:objects
ID: 20393891
try running the applet on a non-vista machine
and the server if possible.
maybe some windows firewall interfering with the request
0
 
LVL 92

Expert Comment

by:objects
ID: 20393896
> Does this make a difference?

it can, but only u can test it :)

0
 

Author Comment

by:KhaiPi
ID: 20393916
I have tried it on a Server 2003 machine (both applet and servlet) and the same thing happens.  And it does work from my Vista machine when I access the servlet on the author's machine.
0
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
ID: 20393955
can u possibly try a different container, am not at all familiar with winstone
0
 

Author Comment

by:KhaiPi
ID: 20393958
Yes, I think I will have to as I cannot see any other reason why it works in one context and not in another.

I will try another container and report back.  Thanks for all your efforts.
0
 

Author Closing Comment

by:KhaiPi
ID: 31412261
I tried the servlet with GlassFish and it works without any problems so it has something to do with Winstone.  Given that GlassFish is the final deployment platform, this is a good outcome!  Thanks, KP.
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

Title # Comments Views Activity
Convert ArrayList of custom objects to JSON 4 53
countHi challenge 25 84
nestparen challenge 4 56
Image decoding from Camera 3 44
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial will introduce the viewer to VisualVM for the Java platform application. This video explains an example program and covers the Overview, Monitor, and Heap Dump tabs.

707 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

18 Experts available now in Live!

Get 1:1 Help Now