Hot questions for Using Applets in servlets

Question:

my scenario is like i invoke applet API from javascript whose return statement is boolean, but i unable to get boolean response from that method.

let me tell what happening inside that method

  1. from js control is going to applet method abc()

  2. inside abc() method i am invoking servlet which is does some process at server end and returns response which i am getting with out any issues.

  3. after this i am doing some regular java stuff and trying to return true or false

  4. I am not getting this response in javascript

Note: This points may be helpful to figure out the issue

1.My applet implements runnable interface which is used for show confirmation dialog to use developed using swing components, this code triggers in some scenarios not every.

  1. I use servlets which returns json response Let me know if you need any details

  2. I am using below function in foreach

    function abc()
    {
      var status = printerApplet.startBulkPersoProcessing(a, b, c);
                        alert("Is it coming here:::");
                        alert(status);
     }
    

This status is not printed what ever we do.


Answer:

first you should make sure you declared your applet like the following :

<APPLET code="MyApplet.class" height="0" id="myApplet" name="myApplet"
                                    archive="/path/to/MyApplet.jar"></APPLET>

after that to call MyApplet from JS like the following :

function callMyAppletFromJS() {
            alert("callMyAppletFromJS");
                document.getElementById('myApplet').jsAppletCall();
      }

in your applet call the JS back like the following :

public void jsAppletCall() {
      //       do you java stuff here 
      // then 
      // call the javascript from the applet using the JSOBject 
              JSObject win = JSObject.getWindow(this);
              win.eval("callJSFromMyAppletMessage();");
     }

and the JS function to be called from the applet like the following :

function callJSFromMyAppletMessage() {
     alert("callJSFromMyAppletMessage");
      }

so the way to call the JS from applet is using the JSObject , please check the docs here for the JSObject as it describes the use for this class .

also as @Hemant mentioned , please check the oracle tutorial here about this subject .

Note : but please be aware if you are calling your applet from JS , even if its signed applet , it will be treated as unsigned applet , check the oracle docs here .

Hope that Helps .

Question:

I had a problem a while back where Chrome and Firefox were changing the sessionid when creating a connection from an applet to a backing bean via a servlet in JSF (see here). I got around it last time by manually setting the sessionId on the HttpURLConnection connection.

The applet requests a ranking criteria object from the backing bean via the servlet. The user then customises the ranking criteria in the applet (and, in other code, submits the ranking criteria back to the backing bean in order to rank products according to the newly customised ranking criteria).

Now Chrome is setting the request sessionId to null, but Firefox and Internet Explorer work fine.

In the applet:

try
    {
        // Get the URL for the servlet.
        URL url = new URL(getCodeBase(), "editCriteriaServlet");

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "text/plain");
        connection.setRequestProperty("Cookie", "JSESSIONID=" + sessionID);

        ObjectOutputStream out = new ObjectOutputStream(connection.getOutputStream());
        out.writeObject("Request criteria Object");
        out.flush();
        out.close();

        // Read in the search criteria object.
        ObjectInputStream in = new ObjectInputStream(connection.getInputStream());
        SealedObject sealedObject = (SealedObject)in.readObject();
        in.close();

        // Decrypt the sealed object and get the zipped data.
        SecretKey key = buildSecretKey(crypKeyString);
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte[] baos = (byte[]) sealedObject.getObject(cipher);
        ByteArrayInputStream gis = new ByteArrayInputStream(baos);

        // Unzip and recover the original object.
        GZIPInputStream unzipped = new GZIPInputStream(gis);
        ObjectInputStream ois = new ObjectInputStream(unzipped);
        tempMultipleSlideDataObject = (MultipleSlideDataObject15) ois.readObject();            
    }
    catch (MalformedURLException ex)
    {
        errorMessage = "Submit criteria file Malformed URL." + ex.toString();
        fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "showErrorMessageDialog_"));
        System.out.println("Model_CriteriaInterface: loadCriteriaObject: MalformedURLException occurred");
    }
    catch (Exception e)
    {
        errorMessage = "Submit criteria file ERROR exception:" + e.toString();
        fireActionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "showErrorMessageDialog_"));
        System.out.println("Model_CriteriaInterface: loadCriteriaObject: Submit criteria file ERROR exception: " + e.toString());
    }

In the servlet:

@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
{
    System.out.println("Servlet: SessionID: " + ((HttpServletRequest)request).getRequestedSessionId());

    response.setContentType("application/x-java-serialized-object");

    try
    {
        ObjectInputStream in = new ObjectInputStream(request.getInputStream());
        in.close();

        // Get the backing bean and then use that to get the search criteria object.
        ProductSelectionBean productSelection = (ProductSelectionBean)request.getSession().getAttribute("productSelectionBean");

        Object searchObject = productSelection.getSealedRankingCriteria();

        // Send the object, in the response, back to the applet.
        ObjectOutputStream outputToApplet = new ObjectOutputStream(response.getOutputStream());
        outputToApplet.writeObject(searchObject);
        outputToApplet.flush();          
        outputToApplet.close();
    }
    catch (ClassNotFoundException ex)
    {
        Logger.getLogger(EditCriteriaServlet.class.getName()).log(Level.SEVERE, null, ex);
    }
}

The following line in the servlet:

System.out.println("Servlet: SessionID: " + ((HttpServletRequest)req).getRequestedSessionId());

-prints 'null' and the 'productSelection' backing bean is null. Firefox and IE print the sessionId fine.

I suspect that this is a bug in Chrome, however, no one from Chrome has gotten back to me. Any thoughts? Suggestions to get around it?

Edit update - I found the proper Chrome reporting site (I was Googling Chrome instead of Chromium) here. Will see if they get back to me through this.

Many thanks in advance.


Answer:

I am not exactly sure if this is what fixed the problem or not, on Chrome, but fixing the:ViewExpiredException exception problem here, using BalusC's answer, also appeared to fix this one as well. Either that or Google's guys have fixed it in the last day or so and it is just coincidence.

Because the problem cookies have been cleared, I have been unable to reproduce the error to check if that was actually the cause of the null pointer problem in Chrome. Why it is only affecting Chrome is any ones guess.

Question:

What is the difference between an Applet and a Servlet and what are a few examples on how each of them are used? I am new to networking am I am wondering how these things are different.


Answer:

From Wikipedia: A Java applet is a small application which is written in Java and delivered to users in the form of bytecode. The user launches the Java applet from a web page, and the applet is then executed within a Java Virtual Machine (JVM) in a process separate from the web browser itself. Applets are used to provide interactive features to web applications that cannot be provided by HTML alone. They can capture mouse input and also have controls like buttons or check boxes. In response to user actions, an applet can change the provided graphic content. This makes applets well-suited for demonstration, visualization, and teaching.

A servlet is a Java programming language class used to extend the capabilities of a server. Although servlets can respond to any types of requests, they are commonly used to extend the applications hosted by web servers. Servlets are the Java counterpart to other dynamic Web content technologies such as PHP and ASP.NET. In other words, a Servlet is an object that receives a request and generates a response based on that request.