Applet Servlet Comm. Problem

Dear friends,
i have an applet that sends a serialized object to the servlet,the Servlet creates another object and passes it back to the applet.
Everything works fine, till i read the object with:
ObjectInputStream objInputStream = new ObjectInputStream(in);
        show("got object input stream");
         chart = new ChartPanel((JFreeChart)objInputStream.readObject());At this point, i got nothing back.Instead i get a "null"returned on my Java Console.
From JBuilder it works fine
Here is the code
//This is called from the applet in order to load a chart in a panel
private JPanel getChartFromServlet(Object[] parameters) throws Throwable {
  ChartPanel chart=null;
  String server;
   try {
///////////////////////create URL Connection to SERVLET
    if (this.remoteServerMode) {
      this.show("http://10.30.1.38:8080/AppletToServlet/DbServlet");
       server="http://10.30.1.38:8080/AppletToServlet/DbServlet";
     else {
       server="http://localhost:8083/DbServlet";
     //SEND DATA TO SERVLET
     URLConnection servletCon=this.getServletConnection(server);
     // servletCon.setRequestProperty("Content-Type","application/octet-stream");
      //send the query parameters  using serialization
       ObjectOutputStream out=new ObjectOutputStream(servletCon.getOutputStream());
       out.writeObject( parameters);
       out.flush();
       out.close();
       this.show("Finish with send to servlet");
       //GET DATA FROM SERVLET
       InputStream in=servletCon.getInputStream();
       show("got input stream");
       ObjectInputStream objInputStream = new ObjectInputStream(in);
        show("got object input stream");
         chart = new ChartPanel((JFreeChart)objInputStream.readObject());
         show("got chart");
        objInputStream.close();
        in.close();
        chart.setPreferredSize(new Dimension(734, 370));
   catch (Exception ex) {
     System.err.println("Exception caught");
     this.show(ex.getMessage());
     this.show(ex.getMessage());
     System.err.println(ex.getMessage());
     ex.printStackTrace(System.err);
   throw new Exception( ex.getCause());
return chart;
//Servlet Side Code
public void doGet(HttpServletRequest request, HttpServletResponse response) throws
      ServletException, IOException {
    ObjectInputStream inputStreamFromApplet=null;
    Object[] queryParams;
  JFreeChart chart=null;
    try {
      response.setContentType("application/x-java-serialized-object");
      //////////////////////////READ INPUT//////////////////////////////////////
      InputStream in=request.getInputStream();
      inputStreamFromApplet=new ObjectInputStream(in);
      //Read applet's serialised object passed in Input Stream
      queryParams = (Object[]) inputStreamFromApplet.readObject();
      //do something with serialized object
      chart=getRequestedChart(queryParams);
      //////////////////////////WRITE OUTPUT////////////////////////////////////
      //open an output stream
      ObjectOutputStream out = new ObjectOutputStream(response.getOutputStream());
      //write to output stream
      out.writeObject(chart);
      out.flush();
      //close output stream
      out.close();
    catch (Exception ex) {
      ex.printStackTrace();
      System.err.println(ex.getMessage());
  }Do you have any ideas?
Apart from the null value,i saw also some SocketException
Is there a security issue involved?Both Servlet and Applet come from the same ip.
Thank you very much in advance,
Chris

A Chart constructor takes as an arg a JFreeChart.
Chart is a JComponent so i cannot serialize it.
That's why the servlet passes a JFreechart object and
the applet constructs a chart from it.
I cast the object to a jfreechart and pass it to the constructor of the chart.
The strange thing also is that, wghile initially with a non perfectly designed UI,everything worked fine but when i modified the applet's UI ,problems started...
Something with serialization and versions of classes?

Similar Messages

  • Applet-Servlet Communication problem EOFException

    Hi! i´ve been searching and searching through forums because it seems this problem is very common, but none of the solutions i´ve seen so far suits me, so i´m here looking for some help because i´ve been stuck one week with this. First of all sorry if my english isn´t the best... i´m a bit rusty...
    Well, i had some code that worked perfectly, but i needed to perform some changes because i needed the servlet to send more info to the applet, and here started the problems, when i made the changes it started to throw EOFException when i was trying to read the InputStream, and furthermore when i came back to the original code it started to throw the exception in the same place too
    So here i am... don´t know what to do now and i entrust to you to give me some tips.
    Here comes some code. This is the original code, the one that runned but it doesn´t run right now
    Applet:
    public ListasComponentesSeleccionables cargarListasComponentes( ) throws IOException, ClassNotFoundException {
              String serv = "/Desaladora/cargarListasComponentesApplet.do";
              String host = Principal.documentBase.getHost( );
              URL direccion = new URL( "http", host, 8080, serv );
              // Create conection
              URLConnection connection = direccion.openConnection( );
              connection.setDoInput( true ); 
              connection.setDoOutput( true );
              connection.setUseCaches( false );
              connection.setRequestProperty( "Content-Type", "application/x-java-serialized-object" );
              ObjectOutputStream output;
              output = new ObjectOutputStream( connection.getOutputStream( ) );
              output.writeObject( new Boolean(true) );
              output.flush( );
              output.close( );
              ObjectInputStream input = new ObjectInputStream( connection.getInputStream( ) ); //<-- Here is the problem
              ListasComponentesSeleccionables response = new ListasComponentesSeleccionables( );
              response = ( ListasComponentesSeleccionables ) input.readObject( );
              return response;
         }Servlet:
    ublic class CargarListasComponentesAppletAction extends Action {
    public ActionForward execute(     ActionMapping mapping,
                                                     ActionForm form,
                                                     HttpServletRequest request,
                                                     HttpServletResponse response )
                            throws ServletException, IOException, Exception  {
              InitialContext context = new InitialContext();
              SensorManagerService sensor_service;
              ActuatorManagerService actuator_service;
              Globals.LOGGER_SECURITY.debug( "Entering ACTION 'CargarListasComponentesAppletAction'" );
              response.setContentType("application/x-java-serialized-object");
              try
                   ObjectInputStream bufferentrada = new ObjectInputStream(request.getInputStream());
                   Boolean peticionOK = (Boolean)bufferentrada.readObject();
                   ObjectOutputStream buffersalida = new ObjectOutputStream(response.getOutputStream());
                   sensor_service = ( SensorManagerService ) context.lookup( "desaladora/SensorManagerServiceBean/local" );
                   ArrayList<AlarmConnectedSensorDTO> sensorList = sensor_service.findAllSensorsToAlarms();
                   actuator_service = ( ActuatorManagerService ) context.lookup( "desaladora/ActuatorManagerServiceBean/local" );
                   ArrayList<AlarmConnectedActuatorDTO> actuatorList = actuator_service.findAllActuatorsToAlarms();
                   buffersalida.writeObject( crearListasSeleccionables(sensorList, actuatorList) );
                   buffersalida.flush();
              catch(Exception e)
                   System.out.println("Error en la trasmision de datos");
              return null;
         private ListasComponentesSeleccionables crearListasSeleccionables(ArrayList<AlarmConnectedSensorDTO> sensorList,
                    ArrayList<AlarmConnectedActuatorDTO> actuatorList) {
              Vector<Integer> vectorSensores = new Vector<Integer>();
              Vector<Integer> vectorActuadores = new Vector<Integer>();
              for(AlarmConnectedSensorDTO sensor : sensorList) {
                   vectorSensores.add(sensor.getIdSensor( ));
              for(AlarmConnectedActuatorDTO actuator : actuatorList) {
                   vectorActuadores.add(actuator.getIdActuator( ));
              ListasComponentesSeleccionables listasComponentesSeleccionables =
                                  new ListasComponentesSeleccionables(vectorSensores, vectorActuadores);
              return listasComponentesSeleccionables;
    }i´ve been running some test in another computer, and this code simply works, but it doesn´t work in the machine i usually work.
    Maybe someway the stream get corrupt? the info i´ve been trying to send and started throwing the exception may still be in the stream? I don´t know what to think right now.
    Hope someone has any idea, thankyou.

    I dont see the problem. However, I suggest you change this;
    System.out.println("Error en la trasmision de datos"); t
    to e.printStackTrace() to see what it is doing when it stops working.
    I also suggest peppering your code with System.out.println() statements to see what it is doing just before stopping.
    Also, try your code with a brand new file with only a few characters in it. If it works, add to it some of your originial file content until it stops working. This way, you can determine if its the file size that is causing the crash or something in the file content. If all else fails, study java I/O and try some other way to read/write the file. You can also try a different browser. If it works, its the browser. Still having problems? Create a new project with a simple applet and file read/write program and get that working. That way, all the other stuff in your original project isn't in the way.

  • Applet servlet communication problem again

    applet send the data to servlet, servlet receive the data and send a message back to applet, but there is an exception error.
    // servlet
    public void doPost (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
         Connection theConnection;
         boolean check = false;
         // Get the value of a request parameter; the name is case-sensitive
            String name = "key1";
            String value = request.getParameter(name);
           try{
                //Loading Sun's JDBC ODBC Driver  
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                theConnection = DriverManager.getConnection("jdbc:odbc:database1", "", "");
                Statement theStatement=theConnection.createStatement();
                String sql = "SELECT col_name FROM table_name WHERE col_name ='"+value+"''";
                ResultSet rs = theStatement.executeQuery(sql);
                if(rs.next()){
                    check = true;
                theStatement.close();//Close statement
                theConnection.close(); //Close database Connection
            }catch (ClassNotFoundException e) {
            System.err.println("ClassNotFoundException : " +e);
            asdf.write(e.toString().getBytes("US-ASCII"));
            } catch (SQLException e) {
                System.err.println("SQL exception : " +e);
                asdf.write(e.toString().getBytes("US-ASCII"));
            if(check){
              try{
                   ObjectOutputStream objStream = null;
                   objStream = new ObjectOutputStream(response.getOutputStream());
                   String message = "your input is already exist in col_name in table_name ";
                   objStream.writeObject(message);
                   objStream.flush();
                   objStream.close();
               catch(Exception ex){
                    asdf.write(ex.toString().getBytes("US-ASCII"));
    //applet
    private void recordSeg()  throws ClassNotFoundException, MalformedURLException, IOException{
                *  Try to connect to the servlet
              try {
                // Construct data
                String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("hello", "UTF-8");
                // Send data to sqlServlet
                URL url = new URL(http://localhost:8084/JSP/sqlServlet");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    // Process line...
                wr.close();
                rd.close();
            } catch (Exception e) {
              //receive data from sqlServlet
            try{
                URL url = new URL(server + "JSP/sqlServlet");
                 URLConnection servletConnection = url.openConnection();
                servletConnection.setUseCaches (false);
                servletConnection.setDefaultUseCaches(false);
    / *+++++++++error line (java.io.IOException: Server returned HTTP response code: 405 for URL: http://localhost:8084/JSP/sqlServlet) */
                ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                String temp_s = inputFromServlet.readObject().toString();
                inputFromServlet.close();
            catch(Exception ex){
                errField.append("Exception ~~~~~~~~~ " +ex+ "\n");
        }

    Sorry, I have put the code tab but ...................................
    applet send the data to servlet, servlet receive the data and send a message back to applet, but there is an exception error.
    //servlet
    public void doPost (HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
         Connection theConnection;
         boolean check = false;
         // Get the value of a request parameter; the name is case-sensitive
            String name = "key1";
            String value = request.getParameter(name);
           try{
                //Loading Sun's JDBC ODBC Driver  
                Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                theConnection = DriverManager.getConnection("jdbc:odbc:database1", "", "");
                Statement theStatement=theConnection.createStatement();
                String sql = "SELECT col_name FROM table_name WHERE col_name ='"+value+"''";
                ResultSet rs = theStatement.executeQuery(sql);
                if(rs.next()){
                    check = true;
                theStatement.close();//Close statement
                theConnection.close(); //Close database Connection
            }catch (ClassNotFoundException e) {
            System.err.println("ClassNotFoundException : " +e);
            asdf.write(e.toString().getBytes("US-ASCII"));
            } catch (SQLException e) {
                System.err.println("SQL exception : " +e);
                asdf.write(e.toString().getBytes("US-ASCII"));
            if(check){
              try{
                   ObjectOutputStream objStream = null;
                   objStream = new ObjectOutputStream(response.getOutputStream());
                   String message = "your input is already exist in col_name in table_name ";
                   objStream.writeObject(message);
                   objStream.flush();
                   objStream.close();
               catch(Exception ex){
                    asdf.write(ex.toString().getBytes("US-ASCII"));
    //applet
    private void recordSeg()  throws ClassNotFoundException, MalformedURLException, IOException{
                *  Try to connect to the servlet
              try {
                // Construct data
                String data = URLEncoder.encode("key1", "UTF-8") + "=" + URLEncoder.encode("hello", "UTF-8");
                // Send data to sqlServlet
                URL url = new URL(http://localhost:8084/JSP/sqlServlet");
                URLConnection conn = url.openConnection();
                conn.setDoOutput(true);
                OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
                wr.write(data);
                wr.flush();
                // Get the response
                BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
                String line;
                while ((line = rd.readLine()) != null) {
                    // Process line...
                wr.close();
                rd.close();
            } catch (Exception e) {
              //receive data from sqlServlet
            try{
                URL url = new URL(server + "JSP/sqlServlet");
                 URLConnection servletConnection = url.openConnection();
                servletConnection.setUseCaches (false);
                servletConnection.setDefaultUseCaches(false);
    / /+error line (java.io.IOException: Server returned HTTP response code: 405 for URL: http://localhost:8084/JSP/sqlServlet)
                ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                String temp_s = inputFromServlet.readObject().toString();
                inputFromServlet.close();
            catch(Exception ex){
                errField.append("Exception ~~~~~~~~~ " +ex+ "\n");
    }

  • Applet servlet communication problem

    applet can receive data but cannot send data to the servlet (i.e. the servlet does not receive anything).
    Listed below are the codes
    //applet
    ObjectOutputStream objStream = null;
            URL url = new URL(getCodeBase(), "/JSP/readAppletServlet");
            URLConnection con= url.openConnection();
            con.setDoInput(true);
            con.setDoOutput(true);
            con.setUseCaches(false);
            con.setDefaultUseCaches(false);
            con.setRequestProperty ("Content-Type", "application/x-java-serialized-object");
           try{
               objStream = new ObjectOutputStream(con.getOutputStream());
               String s = "i come from APPLET";
               objStream.writeObject(s);
               objStream.flush();
               objStream.close();
           }catch(Exception ex){
    //servlet
    public class readAppletServlet extends HttpServlet {
        /** Initializes the servlet.
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
        /** Destroys the servlet.
        public void destroy() {
        protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            java.io.FileOutputStream asdf = new java.io.FileOutputStream(new java.io.File("C:\\13579.txt"));
            InputStream in = request.getInputStream();
            ObjectInputStream inputFromApplet = null;
            String s = " you cannot call servlet ar!!!! try again";
            try{
                inputFromApplet = new ObjectInputStream(in);
                s = inputFromApplet.readObject().toString();
                in.close();
            }catch(Exception ex){
            asdf.write(s.getBytes("US-ASCII"));
            asdf.close();
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
            processRequest(request, response);
        /** Returns a short description of the servlet.
        public String getServletInfo() {
            return "Short description";
    }

    As a (future) programmer the first thing you should learn is never just say "it doesn't work"
    That's what first line support is for to get info out of "dumb" users who don't know better.
    I suggested some code changes but you haven't re posted any code.
    You think it might be the applet but I don't see any exception nor a trace from the applet.
    To turn the full trace on (windows) you can start the java console, to be found here:
    C:\Program Files\Java\j2re1.4...\bin\jpicpl32.exe
    In the advanced tab you can fill in something for runtime parameters fill in this:
    -Djavaplugin.trace=true -Djavaplugin.trace.option=basic|net|security|ext|liveconnect
    if you cannot start the java console check here:
    C:\Documents and Settings\userName\Application Data\Sun\Java\Deployment\deployment.properties
    I think for linux this is somewhere in youruserdir/java (hidden directory)
    add or change the following line:
    javaplugin.jre.params=-Djavaplugin.trace\=true -Djavaplugin.trace.option\=basic|net|security|ext|liveconnect
    for 1.5:
    deployment.javapi.jre.1.5.0.args=-Djavaplugin.trace\=true -Djavaplugin.trace.option\=basic|net|security|ext|liveconnect
    The trace is here:
    C:\Documents and Settings\your user\Application Data\Sun\Java\Deployment\log\plugin...log
    I think for linux this is somewhere in youruserdir/java (hidden directory)

  • Applet- servlet comm.

    Rats!
    The applet keeps throwing a security exception, saying java.io.IOException: bad path: \servlet\myServlet.
    I use getCodeBase() and "/servlet/myServlet" for constructing the URL and the toExternalForm().
    I used http://localhost/servlet/myServlet from the browser from the same location that the applet is and the servlet works fine.
    It' s driving me crazy! It simply does not work.
    Anyone managed to successfully connect an applet to a servlet either with URL, or URLConnection objects?
    Can you tell me how you did it?
    Chris.

    umm
    try it with URLConnection
    This should work.
    URL url = new URL("http://localhost:8080/servlet/yourservlet");
    URLConnection servletConnection = url.openConnection();

  • Applet-servlet communication, object serialization, problem

    hi,
    I encountered a problem with tomcat 5.5. Grazing the whole web i didn't find any solution (some guys are having the same problem but they also got no useful hint up to now). The problem is as follows:
    I try to build an applet-servlet communication using serialized objects. In my test scenario i write a serialized standard java object (e.g. a String object) onto the ObjectOutputStream of the applet/test-application (it doesn't matters wheter to use the first or the latter one for test cases) and the doPost method of the servlet reads the object from the ObjectInputStream. That works fine. But if i use customized objects (which should also work fine) the same code produces an classnotfound exception. When i try to read and cast the object:
    TestMessage e = (TestMessage)objin.readObject();
    java.lang.ClassNotFoundException: TestMessage
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1359)
        at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1205)
        at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:319)
    ...That seems strange to me, because if i instantiate an object of the same customized class (TestMessage) in the servlet code, the webappclassloader doesn't have any problems loading and handling the class and the code works fine!
    The class is located in the web-inf/classes directory of the application. I've already tried to put the class (with and without the package structure) into the common/classes and server/classes directory, but the exception stays the same (I've also tried to build a jar and put it in the appropriate lib directories).
    I've also tried to catch a Throwable object in order to get information on the cause. But i get a "null" value (the docu says, that this will may be caused by an unknown error).
    I've also inspected the log files intensively. But they gave me no hint. Until now I've spend a lot of time on searching and messing around but i always get this classnotfound exception.
    I hope this is the right place to post this problem and i hope that there is anyone out there who can give me some hint on solving this problem.
    Kindly regards,
    Daniel

    hi, thanks for the reply,
    all my classes are in the web-inf/classes of the web-app and have an appropriate package structure. thus the TestMessage class is inside a package.
    i tried some names for the testclass but it didn't matter. the exception stays the same. I also tried to put the jar in the common/lib but the problem stays.
    Well the problem with loaded classes: As i mentioned in the post above i can instantiate an object of TestMessage in the code without any problems (so the classloader of my webapp should know the class!!)
    only when reading from the objectinputstream the classloader doesn't seem to know the class?? maybe theres a parent classloader resposible for that and doesn't know the class?
    strange behaviour...
    p.s. sending the same object from the servlet to the client works well
    regards
    daniel
    Message was edited by:
    theazazel

  • Servlet Applet object communication problem???!!!

    Hy folks,
    I need to validate the ability of complex Servlet Applet communication an run into my first pb right at the beginning of my tests. I need to have around 200 Applet clients connect to my servlet and communicate by ObjectInput and ObjectOutput streams. So I wrote a simple Servlet accepting HTTP POST connections that return a Java object. When the java Applet get instantiated, the Object Stream communication workes fine. But when the Applet tries to communicate with the servlet after that, I can not create another communication session with that Servlet, instead I get a 405 Method not allowed exception.
    Summarized:
    - Applet init() instantiate URLConnection with Servlet and request Java object (opening ObjectInput and Output Stream, after receaving object, cloasing streams).
    - When I press a "get More" button on my Applet, I am not able to instantiate a new URLConnection with my servler because of that 405 exception, WHY???
    Here my Servlet code:
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
             ObjectInputStream inputFromApplet = null;
             ArrayList transmitContent = null;       
             PrintWriter out = null;
             BufferedReader inTest = null;
             try{               
                   inputFromApplet = new ObjectInputStream(request.getInputStream());           
                     transmitContent = (ArrayList) inputFromApplet.readObject();       
                     inputFromApplet.close();
                     ArrayList toReturn = new ArrayList();                 
                     toReturn.add("One");
                     toReturn.add("Two");
                     toReturn.add("Three");
                     sendAnsweredList(response, toReturn);                 
             catch(Exception e){}        
         public void sendAnsweredList(HttpServletResponse response, ArrayList returnObject){
             ObjectOutputStream outputToApplet;    
              try{
                  outputToApplet = new ObjectOutputStream(response.getOutputStream());          
                  outputToApplet.writeObject(returnObject);
                  outputToApplet.flush();           
                  outputToApplet.close();              
              catch (IOException e){
                     e.printStackTrace();
    }Here my Applet code:
    public void init() {         
             moreStuff.addActionListener(new ActionListener(){
                  public void actionPerformed(ActionEvent e){
                       requestMore();
             try{
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");              
                  servletConnection = studentDBservlet.openConnection();      
                   servletConnection.setUseCaches (false);
                   servletConnection.setDefaultUseCaches(false);
                   servletConnection.setDoOutput(true);
                   servletConnection.setDoInput(true);
                   ObjectOutputStream outputToApplet;
                 outputToApplet = new ObjectOutputStream(servletConnection.getOutputStream());          
                 outputToApplet.writeObject(new ArrayList());
                 outputToApplet.flush();           
                 outputToApplet.close(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
                  inputFromServlet.close();
                  outputToApplet.close();             
              catch(Exception e){
                   area = new JTextArea();
                   area.setText("An error occured!!!\n");
                   area.append(e.getMessage());
            getContentPane().add(new JScrollPane(area), BorderLayout.CENTER);
            getContentPane().add(moreStuff, BorderLayout.SOUTH);
        private void requestMore(){
             try{              
                  studentDBservlet = new URL("http://localhost/DBHandlerServlet");                             
                  servletConnection = studentDBservlet.openConnection(); 
                   ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
                   ArrayList studentVector = (ArrayList) inputFromServlet.readObject();
                   area.setText("Success2!\n");
                   for (int i = 0; i<studentVector.size(); i++) {
                        area.append(studentVector.get(i).toString()+"\n");
              catch(Exception e){               
                   area.setText("An error occured2!!!\n");
                   area.append(e.getMessage());
        }Can someone help me solv this issue please, this is my first Applet Servlet work so far so I have no idea on how to solve this issue.

    Sorry folks, just found my error. Forgot about the ObjectInputStream waiting on the Servlet side, so of course had a dead look...
    Sorry!

  • Problem in Applet Servlet communication in cluster

              Our new production server has been configured with
              clusters very recently.The application is running fine if and only if one instance
              of weblogic is running.The application has two applets that communicate through a
              servlet and the servlet is hosted by both the WL servers in the cluster.
              Please consider the following scenario :
              1. JSP#1(having embedded tag for Applet#1) is served by, say, WLInstance#1.
              2. JSP#2(having embedded tag for Applet#2) is served by, say, WLInstance#2.
              3. Applet#1 is loaded by BrowserInstance#1.
              4. Applet#2 is loaded by BrowserInstance#2.
              The way I understand applet-servlet communication is as follows :
              The servlets are invoked through the url-pattern specified in web.xml - if the applet
              is making use of a certain url-pattern that is mapped to servlet, then the call from
              that applet will
              eventually invoke a servlet on any of the two instances till a session is established,
              at which point all subsequent requests from the same browser window/frame will go
              to the servlet hosted on the instance where the http session was created.
              (Please correct me, if I am wrong.)
              So, Applet#1 will always talk to the servlet hosted by WLInstance#1 and Applet#2
              will always talk to the servlet hosted by WLInstance#2.
              In our case, the servlet is maintaining data structures to store all the messages
              sent by diffterent instances of Applets.
              The applets periodically polls the messages from those data structures.Once the messages
              are polled, those are deleted from
              the data structures.
              As there are two different instances of the servlet, Applet#1 never gets messages
              posted by Applet#2.
              Is there a way to make this data structure global to both the servlet instances?
              Thanks and best regards,
              Subir Das
              

              "Subir Das" <[email protected]> wrote:
              >So, Applet#1 will always talk to the servlet hosted by WLInstance#1 and
              >Applet#2
              >will always talk to the servlet hosted by WLInstance#2.
              This statement is not entirely true.
              Suppose WLInstance#1 were to be brought down (for whatever reason), Applet#1 will
              then talk to servlet hosted by WLInstance#2.
              Server pinning could be modified by different load balancing algorithms, configurable
              via containers (or hardware).
              So don't count on which servlet instance your applet is going to be served by.
              Instead consider to give a second look into the design of the servlet data structure
              (object):
              1.Read from data store, if it has been persisted.
              2.If the data is client related then consider sticking the data into session, which
              would then replicate to other WL instances.
              3.Stateless EJB in a cluster ? Don' know much about this(yet).
              My 2 cents..Good luck.
              Rama
              

  • Netscape problem with applet servlet communication

    Netscape always seems to get in the way when you use applets, right?
    I have a nice set of code from a book that shows how to do applet->servlet stuff.
    But although I'm doing this all in the privacy of my own localhost Netscape immediately put a spanner in the works with a security exception and wouldn't let the servlet respond.
    Anyone know what to do here.
    The answer is to use Internet Explorer, possibly, but I'm in linux, and I can't get Opera to work with java yet.
    Anyone got any ideas? Thanks.

    I encountered a security exception with Netscape in Linux when attempting applet-servlet stuff but that's prpbably because I haven't got the plugin for that yet...in fact I don't know if a plugin is available for sure...let me know if you do. As a matter of fact I plan on using the HTMLConverter this weekend to find out if it'll download a plugin.
    The applet-servlet thing runs fine in IE and Netscape on my Windows box as long as the plugins are there and I use the appropriate plugin tags in the HTML
    Post what you find out,
    Brad

  • Applet/servlet communication for byte transmission

    Hello all !
    I wrote an applet to transfer binary file from web servlet (running under Tomcat 5.5) to a client (it's a signed applet) but I have a problem of interpretation of byte during transmission.
    the code of the servlet is :
            response.setContentType("application/octet-stream");
            ServletOutputStream sos = response.getOutputStream();
            FileInputStream fis = new FileInputStream(new File(
                    "C:\\WINDOWS\\system32\\setup.bmp"));
            byte[] b = new byte[1024];
            int nbRead = 1;
            while (nbRead > 0) {
                nbRead = fis.read(b);
                System.out.println("octets lus = " + nbRead);
                sos.write(b, 0, nbRead-1);
            fis.close();
            sos.close();et le code de l'applet qui appelle cette servlet est :
            URL selicPortal = null;
            try {
                selicPortal = new URL(
                        "http://localhost:8080/AppletTest/servlet/FileManipulation");
            } catch (MalformedURLException e) {
                e.printStackTrace();
            URLConnection selicConnection = null;
            try {
                selicConnection = selicPortal.openConnection();
            } catch (IOException e) {
                e.printStackTrace();
            selicConnection.setDoInput(true);
            selicConnection.setDoOutput(true);
            selicConnection.setUseCaches(false);
            selicConnection.setRequestProperty("Content-Type",
                    "application/octet-stream");
            try {
                InputStream in = selicConnection.getInputStream();
                FileOutputStream fos = new FileOutputStream(new File(tempDir
                        + "\\toto.bmp"));
                byte[] b = new byte[1024];
                int nbRead = in.read(b);
                while (nbRead > 0) {
                    fos.write(b);
                in.close();
                fos.close();
             } catch (IOException ioe) {
                ioe.printStackTrace();
            }the file dowloaded is broken. it seems that bytes 01 00 or 00 01 are not correctly process.
    Some ideas to help me please ?

    hi,
    have you solved this issue.. please post me the code since i m also doing the applet/servlet communication and can use your code as reference.
    how to read the content placed in the urlConnection stream in the servlet
    Below is my code in applet
    public void upload(byte[] imageByte)
              URL uploadURL=null;
              try
                   uploadURL=new URL("<url>");
                   URLConnection urlConnection=uploadURL.openConnection();
                   urlConnection.setDoInput(true);
                   urlConnection.setDoOutput(true);
                   urlConnection.setUseCaches(false);
                   urlConnection.setRequestProperty("Content-type","application/octet-stream");
                   urlConnection.setRequestProperty("Content-length",""+imageByte.length);
                   OutputStream outStream=urlConnection.getOutputStream();
                   outStream.write(imageByte);
                   outStream.close();
              catch(MalformedURLException ex)
              catch(IOException ex)
    How can i read the byte sent on the outstream (in above code) in the servlet.
    Thanks,
    Mclaren

  • Applet-Servlet Communication

    On my applet side,I have got a byte array of 10 elements. I want to pass it to a servlet after encoding it through the encode method of URLEncoder class.The byte array is named as byteArray.I am converting the array into a string through the following method
    String str=new String(byteArray);
    String str is passed to servlet after encoding through the method
    URLEncoder.encode(str);
    In the servlet, I am retrieving the byte array with the following command
    str.getBytes();
    But the problem is that every byte that has got 8 or 9 in the decimal place (such as 82, 9F, 8B) is converted into 3F
    When I use the same command ie str.getBytes() in the applet itself, no problem is encountered.
    Can anyone help on this?

    You have to decode the string in servlet by
    String s = URLDecoder.decode("encoded string from applet");
    bytes b[] = s.getBytes();
    You have mentioned that in your applet if you invoke the getBytes() method it is giving the right results. Actually, if you do URLEncoder.encode(s), s won't be encoded. This method will return you an encoded string. You try getBytes() on the String it returned, it won't work (in applet)

  • Asynchronous applet-servlet communication

    Hi all,
    I am trying to implement asynchronous applet-servlet communication and need your help. Anything would help(I tried with synchronous applet-servlet communication but doesn't solve my problem).
    Thanks,

    http://java.sun.com/docs/books/tutorial/networking/index.html
    You can open a socket connection. Bother the client and the server
    can have separate threads for reading and writing and that you gives you
    asynchronous communication. Later, if you think the server is generating
    too many threads and not scaling, you can use features of .java.nio to
    make it more scalable:
    java.nio.channels

  • Is there a good advanced review on applet-servlet communication

    I am working on a web application and unfortunately experiencing a lot of trouble trying to use an applet as front end which interacts with a couple of servlets running on Tomcat. I need to get data from one servlet and send data to another.
    There is a lot of messages posted in this and other forums about how to do this, but none of them got a response pointing to a useful advanced reference on this subject. I have reviewed some of the references given, but couldn't find a thorough detailed advanced reference on applet-servlet communication. For this I mean an exhaustive explanation of the mechanism of communication and when and when is neccesary to use each of the multiple configuration possibilities regarding content-type, message-length, request-method, connection settings, and so on.
    Would anybody be so kind to show me the right direction? As I read the (literally) hundreds of messages posted on this topic, I see this info as widely useful. Most of the topic tracks ends on void or with painful no-way sentences, and maybe many people is avoiding Java technology on web application because of this problem (development delays can abort a project).

    This sample chapter in Java developers' guide to Servlets and Jsp focuses on Applet-Servlet communication, is a pretty good one, and is free :
    http://www.javaranch.com/bunkhouse/samps/2809ch12.pdf
    As to an exhaustive & complete guide that covers absolutely everything, I may be wrong but I doubt you'll find anything like that...unless there is a book somewhere dedicated to the subject.

  • Applet-Servlet or RMI - which is better

    We are in the process of developing a swing-applet based system that requires regular interaction with multiple databases residing on more than one database server.
    The options available before us, as we evaluate are:
    a. Use "signed" applets ( as this is going to be essentially an intra-net application) and use JDBC connection to connect to more than one database ( which reside on servers other than the web server).
    b. Use applet - servlet communication - basically, the servlet would establish connection to the databases, directly or through EJB, retrieve necessary database information and pass on the objects to the applet - the front end GUI would be controlled by the applet.
    c. Use RMI
    We would like to have your perspective of the three options, with your experience in this line.
    The questions that come to us are:
    a. If the system is essentially an intra-net application, is it okay to design with "signed" applet mechanism - how far is this method common in the market and acceptable to the clients? Is it true that the signed applet would be able to establish connection to various "identified servers" that are allowed permissions in the security file?
    b. Between applet-servlet and RMI, which is a better method? What should be the factors that need to be considered? Is RMI being widely used or should we be thinking in terms of EJB, eventhough the current project is purely a Java based solution.
    Your input is highly appreciated - thanking in advance for any suggestions and inputs that you may provide.
    Thanks
    Dixie

    Dixie,
    1) IMHO signed applets are not widely used, but you can use
    ordinary applets, which are accessing other resources through
    redirector servlet on server side - I mean ordinary applets
    are prohibited to establish connect to other than it's own server.
    So you will be forced to have special servlet on your server,
    which have access to other resources on other servers - this is a
    way how to avoid applets limitation.
    2) RMI is a heavy solution, because all parameters/objects should
    be serialized over net and if network connection is unreliable
    working with system will be just a nighmare.
    3) If you think that your network connection is unreliable, you can use HTTP protocol between client and server instead of RMI. In this case
    you will have following benefits:
    i) You can still use all of powerness of thick client
    ii) Network unreliability will be defeated
    iii) Sometime if you would like to port your application to a thin
    client it will be done much more easier than in case of RMI
    4) If you would like to use thin client your only problem will
    be poorness of UI - if you can go with it - go ahead! Otherwise
    use thick client with RMI or HTTP depending on quality of network.
    Paul

  • Applet/Servlet communication - StreamCorruptedException

    Hi, I'm having a problem when I try to connect to a servlet. I am using applet/servlet communication. The problem only occurs when I have lauched a crystal report via http in a new window.
    After the report is launched if I try to hit my servlet I get the following error:
    java.io.CorruptedStreamException: invalid stream header
    Not all crystal reports I launch cause this behavior but I can see nothing in the url I use to launch the report that is out of place or different than other reports.
    APPLET-SERVLET CONNECTION
    try {
    StringBuffer path = new StringBuffer();
    path.append(ip);
    path.append("servlet/DatabaseServlet?");
    path.append("option=getRecords&query=").append(URLEncoder.encode(query,"UTF-8"));
    URL url = new URL(path.toString());
    URLConnection servletConnection = url.openConnection();
    servletConnection.setUseCaches(false);
    servletConnection.setDoInput(true);
    servletConnection.setDoOutput(true);
    servletConnection.setRequestProperty("Content-Type", "application/x-java-serialized-object");
    ObjectInputStream inputFromServlet = new ObjectInputStream(servletConnection.getInputStream());
    rc = (RecordCollection) inputFromServlet.readObject();
    inputFromServlet.close();
    } catch (Exception e) {
    e.printStackTrace();
    SERVLET CODE
    Forwards to doPost
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    System.out.println("session id: " + request.getSession().getId());
    this.doPost(request, response);
    LAUNCHING REPORT FROM APPLET
    try {
    String launchURL = host + directory + report + "?promptOnRefresh=0"+ "&" +
    authentication + "&" + key + "&" + startPeriods + "&" + reportYears + "&" + reportTitle + "&" endPeriods "&" + locations + "&" + reportPeriod + "&" + fiscalWeek + "&" + fiscalYear + "&" +time;
    context.showDocument(new URL(launchURL), "_blank");
    } catch (Exception ex) {
    ex.printStackTrace();
    SAMPLE URL THAT CAUSES PROBLEM
    http://localhost:113/Reports/OpenToBuy_3.class?promptOnRefresh=0&user0=rpuser&password0=er34sw1&[email protected]=rpuser&[email protected]=er34sw1&user0@sub2=rpuser&[email protected]=er34sw1&promptex-key="L","L1","ALL"&promptex-start="1"&promptex-years="2004","2004"&promptex-title="Report Title"&promptex-end="1"&promptex-locs="01","03","04","05"&promptex-period="Feb 2004 [04-01]"&promptex-cw="1"&promptex-cy="2004"&promptex-time=-2-52728"
    Everything works fine until I launch this report then I can no longer get data from my servlet. I thought the URL lenght for the report might be the problem but I lauch a report with a URL longer than the problem one and there I don't get the errors after. When I try to connect to the servlet the println statement in the doGet method of my servlet doesn't get printed so it's not even making it inside that method in the servlet.
    Anyone have any idea what could be causing this? Anyone have any ideas what would be causing this? I'm really stumped.

    I've seen this problem before. Because your accessing a complete URL (ie http://<host>:<port>/xxx), you are actually creating a new session. Whenever the applet opens a connection to a servlet it is running on it's own session not the same as the JSP. This is rather obvious since the Page and Applet are separate entities.
    Try sending authentication with the url. I think the syntax is:
    username:password@http://localhost/xxx
    However I'm not sure how well this might work for Tomcat. As for Java it may try and throw a MalformedURLException I would have to test it first - it's been a long time since I used this technique!
    Wish I could be more help,
    Anthony

Maybe you are looking for

  • Custom IKM Knowledge Modules are not working with Group By Clause

    Hi All,    I am facing an issue with custom IKM knowledge modules. Those are IKM Sql Incremental Update and IKM Sql Control Append. My Scenario is 1. Created an interface with table on source and temporary datastore with some columns in target. 2. In

  • How do I apply JCE Jurisdiction Policy Files in oracle jvm

         I have some java procedure using AES, while the default key size limit is 128.      For local java, I can easily replace Jurisdiction Policy Files in JDK OR JRE,  But I do not know how to do such thing in oracle database(11g2) jvm

  • Meeting Place 8.0 Audio Recording play back

    Hi, We are currently using Meeting place 8.5, it is currently installed as Express Media server (Single server solution) as audio only conferencing solution. I am able to record a meeting using meetingplace conference manager, but there is no option

  • Customer wants 3 or 4level of discount in in one payment term .

    Dear All, I want to know is it possible more then 2 stages of discount in one payment term? If yes then how? Pls guide me. Regards Archana Sharma

  • Enhancing FI_GL_1

    Hi friends I have a requiement to enhance the FI_GL_1 extractor. Now the extractor is bringing in only the local currencies. Now i neeed to populat the Group currencies as well . I looked into GLT0 table where these currencies are maitained and the e