Servlet/applet problem

hi guys
my problem is that, i started my tomcat server, also my servlet. this servlet should call an applet. so here are my questions:
where must be the applet class file?
how looks like my codebase?
what code must i type into the servlet? something special?
do i need an apache server additional?
yes? where must be my files? :)
hope anyone can help me...
bye

keep the applet class file in the home directory, the directory in which your index.html lies, index.html -- the html which shows up when you say http://localhost:8080
and then give the applet description like this in the servlet
out.println("<applet code=\"myApplet.class\" codebase=\"http://localhost:8080\" width=\"400\" height=\"400\"> ");
out.println("</applet>");
and that should work and you will be good to go

Similar Messages

  • 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!

  • Servlet/Applet communication, data limit?

    I have an applet that uses a servlet as a proxy to load/retrieve images from an Oracle database. I have a problem when trying to retrieve images larger than 9-10kb from the database. When using JDBC from a Java Application I don't have any probelms but through the Applet-Servlet configuration I do.
    I use the following code in the Applet:
    URL url =new URL("http","myserver",myport,"/servlet/MyServlet");
    HttpURLConnection imageServletConn = (HttpURLConnection)url.openConnection();
    imageServletConn.setDoInput(true);
              imageServletConn.setDoOutput(true);
              imageServletConn.setUseCaches(false);
    imageServletConn.setDefaultUseCaches (false);
    imageServletConn.setRequestMethod("GET");
    byte buf[] = new byte[imageServletConn.getContentLength()];
    BufferedInputStream instr = new BufferedInputStream(imageServletConn.getInputStream());
    instr.read(buf);
    Image image = Toolkit.getDefaultToolkit().createImage(buf);
    // then code to display the image
    And the following for the Servlet:
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    response.setContentType("image/gif");
    byte[] buff = loadImage(); // this method returns a byte array representing the image.
    response.setContentLength(contentLength);//contentLength is the size of the image
    OutputStream os = response.getOutputStream();
    os.write(buff);
    os.close();
    thanks in advance!

    thanks for your replay,
    I tried your suggestion but whatever I do it seems that tha applet only brings the first 5-10k of the image from the servlet. This is the value I get from instr.read() or any other type of read method. The value of bytes is not always the same.
    Now I also have something new. For images greater than 100k or so I get this error:
    java.io.IOException: Broken pipe
         at java.net.SocketOutputStream.socketWrite(Native Method)
         at java.net.SocketOutputStream.socketWrite(Compiled Code)
         at java.net.SocketOutputStream.write(Compiled Code)
         at java.io.BufferedOutputStream.write(Compiled Code)
         at org.apache.jserv.JServConnection$JServOutputStream.write(Compiled Code)
         at java.io.BufferedOutputStream.write(Compiled Code)
         at java.io.FilterOutputStream.write(Compiled Code)
         at interorient.DBProxyServlet.doGet(Compiled Code)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at javax.servlet.http.HttpServlet.service(Compiled Code)
         at org.apache.jserv.JServConnection.processRequest(Compiled Code)
         at org.apache.jserv.JServConnection.run(Compiled Code)
         at java.lang.Thread.run(Compiled Code)
    I am using the Oracle Internet application server (ias 9i) which actualy uses the apache web listener.
    It seems that this servlet-applet communication is really unstable. If you have anything that may help me it will be greatly appriciated. You can even e-mail me at [email protected]
    thanks!

  • InitialContext - Applet Problem

    Hi,
    When i try to get InitialContext from Applet ( running from appletviewer),
    i'm hitting this error. Please help me to solve this problem
    Exactly this line gives the error
    InitialContext ic = new InitalContext ( hEnv )
    Error:
    javax.naming.NoInitialContextException: Cannot Instantiate class:
    weblogic.jndi.WLInitialContextFactory
    -regards
    Abdul Malik

    you can use applet to pull data periodically from the servlet.
    mj
    "Anthony A." wrote:
    What if you want to perform some type of 'realtime' push from the server?
    Anthony
    "minjiang" <[email protected]> wrote in message
    news:[email protected]...
    why do you have to call your ejbs in applet directly? Why not use aservlet in
    between?
    The overhead of downloading so many so big jar files to the client machinewill
    kill/time out any broswer http session.
    mj
    Abdul Malik wrote:
    Dear Friends,
    After 5 days of struggle, somehow i was managed to access the EJB from
    Applet. But very slow coz of Big Jar files ( can make it bit small by
    identitfying required classes ). I dont know this is correct approach
    or
    not, but works ( damn slow )
    What i did was
    1) Installed the Latest Plugin 1.3.1
    2) Downloaded HTMLConverter tool from java.sun.com and converted my
    html file to use plugin.
    3) inlcuded few jar files in archive tag.
    The files i added in archive tag is
    1) myapplet.jar ( applet classes )
    2) weblogicaux.jar ( !!!!!!!!!!!! quite big jar file )
    3) weblogicclass.jar ( jarred all the classes from classes\weblogicfolder
    (!!!!!!!!!! so big jar file !!!!!! )
    4) myejb.jar ( suppose to work with home and remote class, but notworking
    ( looking for container generated files). so i added my EJB.jar file.dont
    know why ?????????? )
    then it works.
    well, i am not happy with this kind of approach. if any body haveefficient
    one, please kindly post it.
    Note: i tried in 1.2.2 plugin ( works )
    Environment: Windows 2000 / Windows 98, Weblogic 5.1 Service pack 7
    -regards
    Abdul Malik
    "Daniel Hoppe" <[email protected]> wrote in message
    news:[email protected]...
    Anthony,
    why should he place j2ee.jar in the applet classpath? Shouldn't be there
    actually. Your problem seems to be related to a class which is not
    serializable.
    Daniel
    -----Ursprüngliche Nachricht-----
    Von: Anthony A. [mailto:[email protected]]
    Bereitgestellt: Freitag, 22. Juni 2001 18:10
    Bereitgestellt in: jndi
    Unterhaltung: InitialContext - Applet Problem
    Betreff: Re: InitialContext - Applet Problem
    As a test, try to place the j2ee.jar and weblogic.jar in your
    <archive tag>.
    I have this code in my applet's init() method and it fails
    due to a JMS
    Exception.
    I'm using BEA's web server, jndi server, and app server on
    the same box as
    the client.
    Thanks,
    Anthony
    code:
    Hashtable ht = new Hashtable();
    ht.put(Context.INITIAL_CONTEXT_FACTORY,
    "weblogic.jndi.WLInitialContextFactory");
    ht.put(Context.PROVIDER_URL, "t3://anthony01:7001");
    System.out.println("creating context");
    InitialContext ctx = new InitialContext(ht);
    error:
    JMSException: weblogic.jms.common.JMSException:
    java.rmi.MarshalException:
    failed to marshal public abstract weblogic.jms.client.JMSConnection
    weblogic.jms.frontend.FEConnectionFactoryRemote.createConnecti
    on(weblogic.rj
    vm.JVMID,weblogic.jms.client.JMSCallbackRemote) throws
    javax.jms.JMSException,java.rmi.RemoteException; nested exception is:
    java.io.NotSerializableException: weblogic.jms.client.JMSCallback

  • Servlet Compilation Problem !

    Hi,
    I am just starting to learn servlets and I got problem in compiling them. I got compilation error in
    import javax.servlet.*;statement. Seems that the compiler cannot find the servlet package. I got J2EE 1.4 beta installed on my machine but there is no servlet.jar package. I am using J2SDK 1.4.1_02, J2EE 1.4 beta and Tomcat 4.1.24.
    Can anyone help me with my servlet compilation problem?
    Thanks in advance!
    Josh

    servlet.jar is here :
    <tomcatdir>\common\lib
    add it to your compiler classpath

  • Servlet chaining problem..

    import java.io.*;
        import javax.servlet.*;
        import javax.servlet.http.*;
        public class Deblink extends HttpServlet {
          public void doGet(HttpServletRequest req, HttpServletResponse res)
                                       throws ServletException, IOException {
            String contentType = req.getContentType();  // get the incoming type
            if (contentType == null) return;  // nothing incoming, nothing to do
            res.setContentType(contentType);  // set outgoing type to be incoming type
            PrintWriter out = res.getWriter();
            BufferedReader in = req.getReader();
            String line = null;
            while ((line = in.readLine()) != null) {
              line = replace(line, "<BLINK>", "");
              line = replace(line, "</BLINK>", "");
              out.println(line);
          public void doPost(HttpServletRequest req, HttpServletResponse res)
                                        throws ServletException, IOException {
            doGet(req, res);
          private String replace(String line, String oldString, String newString) {
            int index = 0;
            while ((index = line.indexOf(oldString, index)) >= 0) {
              // Replace the old string with the new string (inefficiently)
              line = line.substring(0, index) +
                     newString +
                     line.substring(index + oldString.length());
              index += newString.length();
            return line;
    What is pre request fo above code to work.
    I had tried this many time but it is not working, what will be calling servlet look like

    And can you explain why your title is "Servlet chaining problem"?

  • Applet - Servlet - Database - Servlet- Applet

    Hi All,
    I am using Oracle8i and IE 5.0. I am trying to retrieve the data from a db table and display it.
    Sequence is as following:
    1. Query passed to the applet.
    2. Servlet excutes this query using JDBC and returns the resultset to applet.
    3. Applet displaysthe results.
    Is there anybody who has a code sample to do this, my id is [email protected] ? I am totally new to java and servlets. I would really appreciate any help.
    Thanks a lot.
    Manuriti
    [email protected]

    I've never dealt with the code to handle the applet portion of what you're trying to do, but I can help you with the servlet stuff.
    Your servlet should contain code to accomplish the following steps:
    1. Load an Oracle JDBC driver into memory.
    2. Open a JDBC connection to the Oracle database.
    3. Create a JDBC Statement object which contains the appropriate Oracle SQL code.
    4. Execute the Statement object, which will return a ResultSet.
    5. Read the ResultSet data.
    6. Pool or close the Statement and Connection objects.
    All of these steps are simple. Here's what they might look like in practice:
    // load the Oracle driver
    Class.forName("oracle.jdbc.driver.OracleDriver");
    // open the connection
    String cs = "jdbc:oracle:[email protected]:1521:DBNAME"; // connection string
    String userName = "scott";
    String password = "tiger";
    Connection con = DriverManager.getConnection(cs, userName, password);
    // create a Statement object
    Statement stmt = con.createStatement();
    // create a ResultSet object
    ResultSet rs = stmt.executeQuery("select * from DUAL"); // your SQL here
    // INSERT CODE HERE TO READ DATA FROM THE RESULTSET
    // close the Statement object
    stmt.close();
    // close the Connection object
    con.close();
    So that's how you get data from your Oracle database. Now, how do you pass it to your applet? Well, this is hardly trivial. Typically, servlets return an HTML-formatted text stream. It is possible to have an applet communicate with a servlet, but that raises security issues that I don't fully understand. I believe you would have to have your user's browsers set to the lowest possible security settings, otherwise the browser won't let the applet open a socket to a foreign IP, but again, I'm shaky on that one.
    Anywho, let me know if this was of help and if you have more questions on the servlet/applet stuff. I can probably help you with more specific questions,.

  • 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.

  • Servlet-Applet project. Architectural problem.

    Hello, everybody!
    I'm to make client-server web project, client works with different databases via server (using servlet). The protocol of the project is as follows:
    - Client requests to �erver and gets applet.
    - All communications between client and server are to be made via applet-servlet. So, client makes some operations using applet, then sends data to server. After the data being processed on the server side, client gets the possibilities to make further operations.
    The problem is choosing the proper architecture. Having sigle applet and processing communications with single applet-servlet is not good, because I need to get client the possibility to choose database, then choose table, edit records and so on. I want to have applets for every type of operations. I mean, after client gets start applet, he sends the request to server, which processes it and gets another applet for database choosing and so on.
    The question is: is it possible to build such architecture with many applets and data transfers between them?

    Why does it need to be through applet?
    Why can't the same applet take care of most (all?) your database chores?

  • Servlet/applet/socket problem

    Hi there,
    my problem is this...
    i create a page with an servlet whicht shows an applet. this applet connects to a server through an socket. it works fine, but, when i change the page and the applet is not longer on the screen, the socket connection will be not killed! i dont know why. but i must kill it when the applet is not longer on the screen...whats wrong? can you help me?
    matthias

    Are you overriding the destroy() method in your Applet? This will be called when the applet is about to be unloaded from the browser. Or, as a slightly different alternative, you can override the stop() method, which is called when the applet is scrolled off the screen. Usually when stop() is used, start() is overriden as well to allow the applet to resume when it is scrolled back into view. For more info, read up on the applet lifecycle.

  • 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)

  • Servlet applet object io streams

    hi! i have an applet and servlet which communicate through objectoutputstreams.
    here's part of my applet code found in the init method:
    hostServlet = new URL( "http://localhost:8080/scheduler/servlet/EditSchedule" );
    hostConnection = (HttpURLConnection)hostServlet.openConnection();
    hostConnection.setRequestMethod( "POST" );
    System.out.println( "connected" );
    //set headers
    hostConnection.setDoInput( true );
    hostConnection.setDoOutput( true );
    hostConnection.setUseCaches( false );
    hostConnection.setDefaultUseCaches( false );
    hostConnection.setRequestProperty( "Content-Type", "application/x-java-serialized-object" );
    //stream to servlet just to specify that we're using post not get
    oos = new ObjectOutputStream( hostConnection.getOutputStream() );                                      
    oos.writeObject( "inside" );                                                
    oos.flush();
    oos.writeObject( "inside2" );
    oos.flush();
    //get objects being passed by servlet
    ooi = new ObjectInputStream( hostConnection.getInputStream() );
    here's part of my servlet code in the doPost() method:
    ObjectOutputStream oos = new ObjectOutputStream( response.getOutputStream() );
    ObjectInputStream ois = new ObjectInputStream( request.getInputStream() );
    response.setContentType( "application/x-java-serialized-object" );
    oos.writeObject( object );               
    oos.flush(); 
    oos.close();     
    //read objects
    FileOutputStream fw = new FileOutputStream( "c:\\objectsRead.txt" );
    ObjectOutputStream objectFw = new ObjectOutputStream( fw );
    objectFw.writeObject( "from servlet" );
    objectFw.flush();                                 
    String inside = (String)ois.readObject();
    objectFw.writeObject( inside );
    objectFw.flush();
    String outside = (String) ois.readObject();
    objectFw.writeObject( outside );
    objectFw.flush();
    objectFw.close();both the inside and inside2 objects get written to my textfile. Although, in my applet, if i outputted inside2 after creating the objectinputstream, only inside1 gets written. This is my problem. I have to write back to the servlet way passed the ooi instantiation of the applet. Specifically, in an event handler outside the init method.
    any help would be greatly appreciated! =)

    another weird thing that i found out.
    when i use the syntax:
    oos.writeObject( "something" );
    -->it gets passed to the servlet while
    String str = "something";
    oos.writeObject( str );
    -->doesn't get passed.
    hmm....
    i tried setting the content type to application/octet-stream but still nothing.

  • Inconsistent Stream responses b/w servlet & applet

    Hi all,
    I am facing problem with my servle/applet communication .I am using serialized object transport b/w the two. I am able to send my object using a URL connection class successfully to the server .
    However having problems while reading the response on the applet .
    It's been so incosistent that I sometimes think of switching over to some activex control instead of an applet .
    I have been struggling with this one for quite sometime . Somebody help to fix this out!
    First to the problem faced by me
    Some times I get StreamCorruptedException saying Input stream does not contain serialized object .
    Some times I get EOFException saying Invalid Header-1.
    Why so much inconsistency when I am passing the same serialzed object CStreamData? Anyone's valueable input is highly appreciated.
    My part of code that reads the object sent from the servlet.
    public CStreamData ReadResObj(CServerRequest oRequest)
    CStreamData objResponse = null;
    isServerRunning = true;
    try {
    URL url = new URL( "http://localhost:8080"+
    "/apps/servlet/MWServer");
    URLConnection con = url.openConnection();
    con.setUseCaches(false);
    con.setRequestProperty("CONTENT_TYPE","application/octet-stream");
    con.setDoInput(true);
    con.setDoOutput(true);
    ObjectOutputStream out = new ObjectOutputStream(con.getOutputStream());
    out.writeObject(oRequest);
    out.flush();
    out.close();
    ObjectInputStream ois = new ObjectInputStream(con.getInputStream());
    //The exception is thrown here while reading...
    objResponse = (CStreamData)ois.readObject();
    ois.close();
    }catch (Exception e)
    isServerRunning = false;
    return (CStreamData)objResponse;
    return (CStreamData)objResponse;
    }//End of readResObj
    Best rgds,
    prithvi

    It would be interesting to see what's the response of your servlet.
    Mybe the response of your servlet is an error html page
    which of course can't be converted into Object of Type CStreamData.
    You should think about doing some error handling before you try read from the ObjectInputStream an before you think about using ActiveX components.
    for example
    URLConnection con = url.openConnection();
    HttpURLConnection httpConnection;
    try
      URL url = new URL( "http://localhost:8080"+"/apps/servlet/MWServer");
      URLConnection con = url.openConnection();
      httpConnection = (HttpURLConnection)con;
      out.close();
      if(  httpConnection.getResposeCode() == HttpURLConnection.HTTP_OK )
         ObjectInputStream ois = new ObjectInputStream(con.getInputStream());
         objResponse = (CStreamData)ois.readObject();
         ois.close();
    }If you still have problems dump the content of your servlet response
    to the console and tell what you see or post parts of the response.

  • Communication between servlet & applet

    Hello everybody,
    Well, I have a problem with my applet/servlet system.
    I Would like my applet to send some queries to the servlet.
    However, I don't know how to link the applet with the servlet (the only way I know is to use "openConnection()", but I don't see how to incorporate my query in the URLConnection (in order to have one, I need openCOnnection, and once it's done, well, the doGet method has already be laucnh, without any parameter to read). In my case, the DoGet methods of the servlet is launched, and of course, the HTTPRequest is almost empty, seeing thath I don't see how to specify the differnets parameters.
    Is thereany simple meaning to make the applet communicate this the servlet, sending strings, and receiving objects (I have already solve the problem of the sending of an object from the servlet to the applet, in the doGet method).
    Thank you very much
    C U

    In the applet html include a servlet parameter.
    <param
    name="servlet"
    value="/SqlServlet" />
    In your applet open a connection to servlet.
    InputStream in = null;
    URLConnection conn = null;
    URL url = null;
    String servlet = getParameter("servlet");
    url = new URL(servlet + "?sql=" + URLEncoder.encode(sql));
    conn = url.openConnection();
    in = conn.getInputStream();

Maybe you are looking for

  • Hi can anyone tell me if the macbook A1278 (5,1) is a pro??

    Hi can anyone tell me if the macbook A1278 (5,1) is a pro?

  • GETTING STARTED

    Hello folks, i'm a novice to Javacard. though i'm into a bit of java programming. what do i need to get started?

  • Zen Touch or Zen Mi

    Hi, I want to get a digital music player but I'm in a bit of a dilemma. The Zen Touch and Micro are the same price but obviously the Touch has four times the capacity of the Micro. The problem is I only have 3.8GB of music and while I might get a bit

  • Screen at start up SAP B1

    Hi, every body. I don't know to make a screen at start up SAP B1 is moved, for Example: a picture wave ripple of SAP at start up.

  • Large Image Zoom Slider not working

    Can anyone help with why my Large Image Zoom slider doesn't work? I've followed instructions as per tag: {tag_largeimage,zoom,width,height} I have dimensions at 310 and 220. Image looks ok but slider desn't move and image doesn't get bigger...