Pass byte[] from applet to servlet

I have an application that allows users to copy an image from the system clipboard into a frame. What I would like to be able to do, is save that image into a database (db2 on as/400). In order to do that, I try to send the image, which I turned into a byte[] in order to easily insert into the database, from the applet to the servlet using streams (no actual file io), but the image always comes up null when I pass it to the servlet. What am I doing wrong? The image gets copied and drawn from the clipboard just fine, but I can't send it to the servlet. I only included the part of the servlet that tries to retreive the byte array. I know the applet code is a little long, but I figured it might be of interest to someone. Please help!
Here's the code for the applet:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.datatransfer.*;
import java.net.*;
import java.io.*;
import javax.swing.ImageIcon;
import java.util.*;
import java.awt.image.*;
public class PicApp extends Applet implements ClipboardOwner
PrintWriter opWriter = null;
private Button cmdPaste = new Button();
private ImageControl destinationImage = new ImageControl ();
private BorderLayout defaultLayout = new BorderLayout ();
public Image tempImage = null;
public ImageIcon transferImage = null;
private String webServerStr = "";
private String hostName = null;
private int port = 80;
private String servletPath = null;
Clipboard clipboard;
//the byte array I try to pass
public byte[] passed = null;
public String passedAction = null;
public void init()
try
opWriter = new PrintWriter( new BufferedWriter( new FileWriter( "pictureDetails.txt" ) ) );
catch(Exception e)
e.printStackTrace();
hostName = getParameter("HostName");
servletPath = getParameter("ServletPath");
passedAction = getParameter("Action");
//setLayout
this.setLayout (defaultLayout);
this.setBackground(java.awt.Color.gray);
cmdPaste.setLabel("Paste Image from Clipboard");
this.add (cmdPaste, BorderLayout.SOUTH);
this.add (destinationImage, BorderLayout.NORTH);
//add action listener
cmdPaste.addActionListener (new cmdPasteActionListener ());
//initialize the clipboard
clipboard = getToolkit().getSystemClipboard();
// get the host name and port of the applet's web server
try
opWriter.println("Picutre Applet Details\n");
URL hostURL = getCodeBase();
opWriter.println("hostURL = " + hostURL.toString() + "\n");
hostName = hostURL.getHost();
opWriter.println("hostIP = " + hostName + "\n");
port = hostURL.getPort();
opWriter.println("port = " + port + "\n");
if (port == -1)
port = 80;
if(passedAction == "" || passedAction == null)
webServerStr = "http://" + hostName + ":" + port + servletPath;
opWriter.println("Web String full = " + webServerStr);
else
webServerStr = "http://" + hostName + ":" + port + servletPath + "?act=" + passedAction;
opWriter.println("Web String full = " + webServerStr);
opWriter.close();
catch(Exception e)
e.printStackTrace();
// INNER CLASSES
class cmdPasteActionListener implements ActionListener
public void actionPerformed (ActionEvent event)
Transferable clipboardContent = clipboard.getContents(this);
//Transferable clipboardContent = Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
if ((clipboardContent != null) && (clipboardContent.isDataFlavorSupported(DataFlavor.imageFlavor)))
try
//display Image
tempImage = (Image)clipboardContent.getTransferData(DataFlavor.imageFlavor);
destinationImage.setImage(tempImage);
int width = (new ImageIcon(tempImage).getIconWidth());
int height = (new ImageIcon(tempImage).getIconHeight());
PixelGrabber pg = new PixelGrabber(tempImage, 0, 0, width, height, true);
passed = new byte[width*height];
passed = (byte[])pg.getPixels();
//send Image
ProcessPicture();
catch (UnsupportedFlavorException e)
catch (IOException e)
}//end of if
else if(clipboardContent == null)
}//end of method
}//end of inner class
public PicApp()
public void lostOwnership (Clipboard parClipboard, Transferable parTransferable)
System.out.println("Lost ownership of clipboard");
protected void ProcessPicture()
try
// connect to the servlet
URL servletURL = new URL( webServerStr );
//URLConnection servletConnection = servletURL.openConnection();
HttpURLConnection servletConnection =(HttpURLConnection)servletURL.openConnection();
// inform the connection that we will send output and accept input
servletConnection.setDoInput(true);
servletConnection.setDoOutput(true);
// Don't used a cached version of URL connection.
servletConnection.setUseCaches (false);
// Specify the content type that we will send binary data
servletConnection.setRequestProperty("Content-Type", "application/octet-stream");
// send the image object to the servlet using serialization
sendImageToServlet(servletConnection);
// now, let's read the response from the servlet.
// this is simply a confirmation string
readServletResponse(servletConnection);
catch (Exception e)
System.out.println(e.toString());
protected void readServletResponse(URLConnection servletConnection)
BufferedReader inFromServlet = null;
try
// now, let's read the response from the servlet.
// this is simply a confirmation string
inFromServlet = new BufferedReader(new InputStreamReader(servletConnection.getInputStream()));
String str;
while (null != ((str = inFromServlet.readLine())))
System.out.println("Reading servlet response: " + str);
inFromServlet.close();
catch (IOException e)
System.out.println(e.toString());
protected void sendImageToServlet(URLConnection servletConnection)
ObjectOutputStream outputToServlet = null;
try
// send the image object to the servlet using serialization
outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
//check size of image
System.out.println(passed.length);
// write objectt
outputToServlet.writeObject(passed);
outputToServlet.flush();
outputToServlet.close();
catch (IOException e)
System.out.println(e.toString());
servlet:
public void performTask(HttpServletRequest request, HttpServletResponse response)
ObjectInputStream inputFromApplet = null;
byte[] ImageFromApplet = null;
PrintWriter out = null;
BufferedReader inTest = null;
try
// get an input stream from the applet
inputFromApplet = new ObjectInputStream(request.getInputStream());
// read the serialized imageIcon data from applet
ImageFromApplet = (byte[])inputFromApplet.readObject();
inputFromApplet.close();
catch(Exception e)
// handle exception
byte[] transferImage = ImageFromApplet;
if(transferImage == null)
System.out.println("Image passed is empty!");

D,
I read your code. I believe you are trying to send the byte array with the wrong outputStream.write method. For a byte[] I have successfully used the form, servletOut.write(byteArray, 0, byteArray.length). You have to tell the receiver how much data will be sent to it so it knows when to stop read in the data.
Example:
_url = new java.net.URL(serverURL);
//Attempt to connect to the host
java.net.URLConnection connection = _url.openConnection();
// Initialize the connection
connection.setUseCaches(false);
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestProperty("Content-type", "application/octet-stream");
BufferedInputStream fileInputStream = new BufferedInputStream(fIS);
int nBytesAvailable = fileInputStream.available();
byte byteArray[] = new byte[nBytesAvailable];
fileInputStream.read(byteArray, 0, nBytesAvailable);
fileInputStream.close();
fIS.close();
// send data to servlet, get outstream, write data, flush, close.
DataOutputStream outStream = new DataOutputStream(connection.getOutputStream());
outStream.write(byteArray, 0, nBytesAvailable);
outStream.flush();
outStream.close();

Similar Messages

  • Problem in sending image from applet to servlet

    dear friends,
    i have a need to send an image from applet to servlet via HttpConnection and getting back that image from applet.
    i am struggling with this sice many hours and got tired by searching any post that would help me but haven't got yet.
    i tried using this code but it dosent make any execution sit right. i got NPE at ImageIcon.getDescription() line;
    at applet side
          jf.setContentPane(getJContentPane());
                     FileDialog fd=new FileDialog(jf,"hi");
                     fd.setMode(FileDialog.LOAD);
                     fd.setVisible(true);   
                     v=new Vector();
                     try{                                                
                               FileInputStream fis=new FileInputStream(new File(fd.getDirectory()+fd.getFile()));      
                               byte[] imgbuffer=new byte[fis.available()];
                               fis.read(imgbuffer);
                               ImageIcon imgdata=new ImageIcon(imgbuffer);
                               v.add(0,imgicon);
                                String strwp ="/UASProject/Storeimage";              
                                URL servletURL = new URL(getCodeBase(),strwp);             
                                HttpURLConnection servletCon = (HttpURLConnection)servletURL.openConnection();       
                                servletCon.setDoInput(true); 
                                servletCon.setDoOutput(true);
                                servletCon.setUseCaches(false);
                                servletCon.setDefaultUseCaches(false);   
                                servletCon.setRequestMethod("POST");     
                                servletCon.setRequestProperty("Content-Type", "application/octet-stream");   
                                servletCon.connect();            
                                ObjectOutputStream oboutStream = new ObjectOutputStream(servletCon.getOutputStream());                     
                                oboutStream.writeObject(v);
                                v.remove(0);
                                oboutStream.flush();      
                                oboutStream.close();  
                                //read back from servlet
                                ObjectInputStream inputStream = new ObjectInputStream(servletCon.getInputStream());
                                 v= (Vector)inputStream.readObject();                     
                                 imgicon=(ImageIcon)v.get(1);
                                 showimg.setIcon(imgicon);
                                 this.getContentPane().validate();
                                 this.validate();  
                                inputStream.close();                                                        
                             //  repaint();
                     }catch(Exception e){e.printStackTrace();}  and this is at servlet side
            try {       
                         Vector v=new Vector();                    
                         ObjectInputStream inputFromjsp = new ObjectInputStream(request.getInputStream());                                      
                          v = (Vector)inputFromjsp.readObject();                                                                                                          
                          imgicon=(ImageIcon)v.get(0);                     
                          inputFromjsp.close();            
                          System.out.println(imgicon.getDescription());                                      
                          v.remove(0);
                          v.add(1,imgicon);
    //sending back to applet
                           response.setContentType("application/octet-stream");
                          ObjectOutputStream oboutstream=new ObjectOutputStream(response.getOutputStream());            
                          oboutstream.writeObject(v);
                          oboutstream.flush();
                          oboutstream.close();
                   } catch (Exception e) {e.printStackTrace();}  i really need your help. please let me out of this headche
    thanks
    Edited by: san_4u on Nov 24, 2007 1:00 PM

    BalusC wrote:
    san_4u wrote:
    how can i made a HttpClient PostMethod using java applets? as i have experience making request using HttpURLConnection.POST method. ok first of all i am going make a search of this only after i will tell. please be onlineOnce again, see link [3] in my first reply of your former topic.
    yeah! i got the related topic at http://www.theserverside.com/tt/articles/article.tss?l=HttpClient_FileUpload. please look it, i am reading it right now and expecting to be reliable for me.
    well what i got, when request made by html code(stated above) then all the form fields and file data mixed as binary data and available in HttpServletRequest.getinputstream. and at servlet side we have to use a mutipart parser of DiskFileItemFactory class that automatically parse the file data and return a FileItem object cotaing the actual file data,right?.You can also setup the MultipartFilter in your environment and don't >care about it further. Uploaded files will be available as request attributes in the servlet.is the multipartfilter class file available in jar files(that u suggested to add in yours article) so that i can use it directly? one more thing the import org.apache.commons.httpclient package is not available in these jar files, so where can got it from?
    one mere question..
    i looked somewhere that when we request for a file from webserver using web browser then there is a server that process our request and after retrieving that file from database it sends back as response.
    now i confused that, wheather these webservers are like apache tomcat, IBM's webspher etc those processes these request or there is a unique server that always turned on and process all the request?
    because, suppose in an orgnisation made it's website using its own server then, in fact, all the time it will not turned on its server or yes it will? and a user can make a search for kind of information about this orgnisation at any time.
    hopes, you will have understand my quary, then please let me know the actual process
    thanks
    Edited by: san_4u on Nov 25, 2007 11:25 AM

  • Passing a file as parameter from applet to servlet

    hi
    i have just started to use servlets. i have developed applet gui interface. when i click the button i want a file "abc.txt" to be send to the servlet. i am doing like this:
    URL serv_url = new URL(null,"http://host:port/xyz/servlet/TestServlet);
    URLConnection connect = (URLConnection)serv_url.openConnection();
    output = new File("abc.txt");
    connect.setDoOutput(true);
    connect.setDoInput(true);
    connect.setUseCaches(false);
    connect.setDefaultUseCaches(false);
    connect.setRequestProperty("content-type","application/x-www-form-urlencoded");
    ObjectOutputStream outputToServlet = new ObjectOutputStream(connect.getOutputStream());
    outputToServlet.writeObject(output);
    outputToServlet.flush();
    outputToServlet.close();
    //for printing purpose on the gui listbox          
    listmodel1.addElement("ConnectingToRemoteServlet");
    BufferedReader in = new BufferedReader ( new InputStreamReader (connect.getInputStream()));
              while((line = in.readLine())!= null)
              listmodel1.addElement("Response:"+line);
              in.close();
    but i am not sure if this is correct. because when i tried to print the file that is send to servlet. it is giving some ascii characters...
    please tell me how to make sure if the file has reached the servlet. or any other method!!
    thanks
    pre_pra

    i don't want to use any third party packages to achieve this. I have looking into forums and i understand that some object serialization stuff has to be done. but i am still not clear abt how to proceed. any example code or details of steps regarding to pass file object from applet to the servlet would be greatly appreciated. i have already spend two full days on this. i wish i can get a better understanding wiht you help
    thanks a lot:)

  • Sending a file from Applet to servlet HELP me Please

    Sorry, i have the problem this is my code Applet & Servlet but it seems working asynchronously if you have some ideas please reply me i send bytes on outputstream but the inputstream of servlet receive nothing bytes but write my system.out.print on screen server:
    Applet:
    URL servletURL = new URL(codebase, "/InviaFile/servlet/Ricevi");
    HttpURLConnection urlConnection = (HttpURLConnection) servletURL.openConnection();
    urlConnection.setRequestMethod("POST");
    urlConnection.setUseCaches(false);
    urlConnection.setDoOutput(true);
    urlConnection.setDoInput(true);
    urlConnection.setAllowUserInteraction(false);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    urlConnection.setRequestProperty("Content-length", String.valueOf(100));
    urlConnection.connect();
    if(urlConnection.HTTP_BAD_REQUEST == HttpURLConnection.HTTP_BAD_REQUEST){
    /*System.out.println("Cattiva Richiesta: "+urlConnection.getContentEncoding());
    System.out.println("Tipo di metodo: "+urlConnection.getRequestMethod());
    System.out.println("Tipo di Risposta: "+urlConnection.getResponseCode());
    System.out.println("Tipo di messaggio: "+urlConnection.getResponseMessage());
    System.out.println("Tipo di contenuto: "+urlConnection.getContentType());
    System.out.println("Tipo di lunghezza contenuto: "+urlConnection.getContentLength());
    System.out.println("Tipo di doinput: "+urlConnection.getDoInput());
    System.out.println("Tipo di doouput: "+urlConnection.getDoOutput());
    System.out.println("Tipo di URL: "+urlConnection.getURL());
    System.out.println("Tipo di propriet� richiesta: "+urlConnection.getRequestProperty("Content-Type"));
    System.out.println("Entra if");
    DataOutputStream dout = new DataOutputStream(urlConnection.getOutputStream());
    InputStream is = urlConnection.getInputStream();
    if(ritornaFile("C:/Ms.tif", dout))System.out.println("Finita lettura");
    dout.close();
    urlConnection.disconnect();
    System.out.println("Fine Applet");
    }catch(Exception e) { System.err.println(e.getMessage());e.printStackTrace();}
    public boolean ritornaFile(String file, OutputStream ots)throws Exception{
    FileInputStream f = null;
    try{
    f = new FileInputStream(file);
    byte[] buf = new byte[4 * 1024];
    int byteLetti;
    while((byteLetti = f.read()) != -1){ots.writeByte(buf, 0, byteLetti);ots.flush();
    while((byteLetti = f.read()) != -1){ots.write(byteLetti);ots.flush();
    System.out.println("byteLetti= "+byteLetti);
    return true;
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    return false;
    }finally{
    if(f != null)f.close();
    Servlet:
    HttpSession ses = request.getSession(true);
    System.out.println("Passa servlet "+request.getMethod());
    System.out.println("Passa servlet "+ses.getId());
    ServletInputStream servletinputstream = request.getInputStream();
    DataInputStream dis = new DataInputStream(request.getInputStream());
    int c = dis.available();
    System.out.println("c="+c);
    //ServletOutputStream servletoutputstream
    //response.getOutputStream();
    response.setContentType("application/octet-stream");
    System.out.println("URI= "+request.getRequestURI());
    System.out.println("pathTranslated: "+request.getPathTranslated());
    System.out.println("RemoteUser: "+request.getRemoteUser());
    System.out.println("UserInRole: "+String.valueOf(request.isUserInRole("")));
    System.out.println("pathInfo: "+request.getPathInfo());
    System.out.println("Protocollo: "+request.getProtocol());
    System.out.println("RemoteAddr:"+request.getRemoteAddr());
    System.out.println("RemoteHost:"+request.getRemoteHost());
    System.out.println("SessionID:"+request.getRequestedSessionId());
    System.out.println("Schema:"+request.getScheme());
    System.out.println("SeesionValido:"+String.valueOf(request.isRequestedSessionIdValid()));
    System.out.println("FromURL:"+String.valueOf(request.isRequestedSessionIdFromURL()));
    int i = request.getContentLength();
    System.out.println("i: "+i);
    ritornaFile(servletinputstream, "C:"+File.separator+"Pluto.tif");
    System.out.println("GetMimeType= "+getServletContext().getMimeType("Ms.tif"));
    InputStream is = request.getInputStream();
    int in = is.available();
    System.out.println("Legge dallo stream in="+in);
    DataInputStream diss = new DataInputStream(servletinputstream);
    int ins = diss.read();
    System.out.println("Legge dallo stream ins="+ins);
    int disins = diss.available();
    System.out.println("Legge dallo stream disins="+disins);
    is.close();
    System.out.println("Fine Servlet");
    catch(Exception exception) {
    System.out.println("IOException occured in the Server: " + exception.getMessage());exception.printStackTrace();
    public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, java.io.IOException {
    processRequest(request, response);
    /** Returns a short description of the servlet.
    public String getServletInfo() {
    return "Short description";
    public void ritornaFile(InputStream its, String fileDest )throws Exception{
    FileOutputStream f = null;
    try{
    f = new FileOutputStream(fileDest);
    byte[] buf = new byte[2 * 1024];
    int byteLetti;
    while((byteLetti = its.read()) != -1){
    f.write(buf, 0, byteLetti);
    f.flush();
    System.out.println("Byteletti="+byteLetti);
    }catch(Exception ex){
    System.err.println(ex.getMessage());
    }finally{
    if(f != null)f.close();

    Hi all,
    Can anyone help me.I am trying to send an audio file from a applet to servlet with HTTP method(no raw sockets), also the servlet shld be able to save the file on the server.Any suggestions welcome.USing audiostream class from javax.sound.sampled.
    The part of applet code which calls servlet is :
    URL url = new URL("http://" + host + "/" + context + "/servlet/UserUpdateWorkLogAudio?userid=" + userId.replace(' ', '+') + "&FileName=" + filename.replace(' ', '+'));
    URLConnection myConnection = url.openConnection();
    myConnection.setUseCaches(false);
    myConnection.setDoOutput(true);
    urlConnection.setRequestProperty("Content-Type", "application/octet-stream");
    myConnection.connect();
    out = new BufferedOutputStream(myConnection.getOutputStream());
    AudioSystem.write(audioInputStream, fileType,out); // IS THIS RIGHT APPROACH?
    ************************end of applet code**********************
    ************************servlet code******************************
    try
    {BufferedInputStream in = new BufferedInputStream(request.getInputStream());
    ????????What code shld i write here to get the audio file stream
    BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
    *********************************************end***********************
    Thanks
    Joe.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

  • Passing values from applet using POST method to PHP page

    Hello there ;)
    I realy need a help here.. I`ve been working all day on sending mail from applet. I didn`t succeed bcs of the security restrictions.
    So I decided just to pass arguments into PHP page, which process them and send e-mail to me.
    So here is the problem.. I need to send String variables througth POST into my php page. Now I`m using GET method, but I need more than 4000 characters.
    My actual solution is:
      URL url = new URL("http://127.0.0.1/index.php?name=" + name + "&message=" + message);
    this.getAppletContext().showDocument(url,"_self");I really need to rewrite it into POST. Would you be so kind and write few lines example [applet + php code]? I`ve already searched, googled, etc.. Pls don`t copy links to other forums here, probably I`ve read it.
    Thanx in advance to all :)

    hi!
    i`ve got some news about my applet.. so take this applet code:
    public class Apletik extends JApplet {
        public void init() { }
        public void start()
        try
          String aLine; // only if reading response
          String  parametersAsString = "msg=ahoj&to=world";
          byte[] parameterAsBytes = parametersAsString.getBytes();
          // send parameters to server
          URL url = this.getCodeBase();
          url = new URL(url + "spracuj.php");
          URLConnection con = url.openConnection();
          con.setDoOutput(true);
          con.setDoInput(true); // only if reading response
          con.setUseCaches(false);
          con.setRequestProperty("Content=length", String.valueOf(parameterAsBytes.length));
          OutputStream oStream = con.getOutputStream();
          oStream.write(parameterAsBytes);
          oStream.flush();
          String line="";
          BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
          while ((aLine = in.readLine()) != null)
           JOptionPane.showMessageDialog(null, aLine);      
           if(aLine.equals("")) break;
          in.close();      
          oStream.close();
        catch (Exception ex)
          JOptionPane.showMessageDialog(null, ex.toString());
    }here is code of spracuj.php which is on server:
    <?php
      if(isset($_POST['msg']))
        echo('hurray!');
    ?>it has only 1 problem.. when i test it on my localhost, everything seems to be all right. but when i post it to my server, i got IOException HTTP 400 error code :( where is the problem? please help me, i`m so close :D thanx

  • Problem while sending seriailized  object from applet to servlet

    Hi I m having Object communication between Applet and Servlet.
    I m getting error stack trace as
    java.io.EOFException
         at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source)
         at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source)
    at java.io.ObjectInputStream.readStreamHeader(Unknown Source)
         at java.io.ObjectInputStream.<init>(Unknown Source)
         at com.chat.client.ObjectClient.write(ObjectClient.java:56)
    at the line
    ObjectInputStream ois = new ObjectInputStream(conn.getInputStream());
    thanks in advance
    Ravi
    the whole code is as follows....
    public Serializable write(Serializable obj) throws IOException,ClassNotFoundException{
              URLConnection conn = serverURL.openConnection();
              conn.setDoOutput(true);
              conn.setDoInput(true);
              conn.setUseCaches(false);
              conn.setRequestProperty("Content-Type", "java-internal/"+obj.getClass().getName());
              conn.connect();
              ObjectOutputStream oos= null;
              try{
              oos = new ObjectOutputStream(
                   conn.getOutputStream());
                        oos.writeObject(obj);
                   catch(Exception ee){
                                       ee.printStackTrace();
                   finally{
                        if(oos!=null){
                             oos.flush();
                             oos.close();
                        return the reponse to the client
                   ObjectInputStream ois=null;
                   try{
    \\this is the line where i m getting the error               
    ois = new ObjectInputStream(conn.getInputStream());
                             return (Serializable)ois.readObject();
                        catch(Exception ee){
                                            System.out.println("Error in Object Client inputstream ");
                                            ee.printStackTrace();
                                            return null;
                        finally{
                             if(ois!=null){
                                  ois.close();

    Did anyone find a fix to this problem. I am having a similiar problem. Sometimes I receive an EOFException and othertimes I don't. When I do receive an EOFException I check for available() in the stream and it appears 0 bytes were sent to the Servlet from the Applet.
    I am always open to produce this problem when I use File->New in IE my applet loads on the new page.. and then I navigate to a JSP sitting on the same application server. When I go to the Applet on the initial page and try to send an object to the server I get an EOFException. No idea!

  • Passing variable from javascript to servlet!!!

    Hi all,
    I have one doubt,
    can we pass a variable from javascript to servlet???
    In Brief,
    i am getting some values in javascript through jsp and the same values i
    want to use in servlet.
    Yes, i know i can get these values in servlet by using request.getParameter("");
    But these values are dynamically generated so i dont know how many varaible are they!. so i am trying to put some array list so that i can forward this values to servlet.
    But i can't get this array which is declared in javascript!! :( so any buddy can help me how to get this dynamically generated values in servlet!!!
    Thanks in Advance!! :)

    can you post a sample of your code?
    remember to put it between tags                                                                                                                                                                                       

  • Passing information from applet  to  java script  of same browser

    Hi
    i want to pass some information from applet button click to same browser window html elements where applet exist. how it can be possible
    Thanks
    Dev

    Use JSObject:
    html file:
         <object classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93"
                  height="0" width="0" >
            <param name="code" value="someApplet.class" />
            <!--[if !IE]> Mozilla/Netscape and its brethren -->
            <object classid="java:someApplet.class"
                    height="0" width="0"
                    mayscript=true>
            </object>
            <!-- <![endif]-->
          </object>
    <LABEL id="lblOutputText">This text is the HTML text </LABEL>applet
    // new class for jsObject!!!! compile this: javac -classpath "C:\Program Files\Java\jre1.5.0\lib\plugin.jar" someApplet.java
    // since jaws.jar does not exsist anymore
    // in 1.4.0 to compile: javac -classpath "C:\j2sdk1.4.0_03\jre\lib\jaws.jar" someApplet.java
    // for msjvm use the -source 1.3 -target 1.1 option so the command looks like this:
    // javac -source 1.3 -target 1.1 -classpath "C:\j2sdk1.4.0_03\jre\lib\jaws.jar" someApplet.java
    import netscape.javascript.*;
    public class someApplet extends java.applet.Applet {
        JSObject win;
        public void init() {
             try{
                 win = JSObject.getWindow(this);
    // you need win.eval("window.close();"); // to close the window. if the current window is not a popup
    // opened by a parent with window.open than the user will get a waring, your next question probably will
    // be "can I stop this warning" and the answer is simple: NO
                 JSObject textBoxLabel = (JSObject) win.eval("document.getElementById('lblOutputText')");
                 textBoxLabel.setMember("innerHTML", "<center><h1>Some text from applet</h1></center>");
            }catch(Exception e){
                 e.printStackTrace();
    }

  • Sending different types of data from applet to servlet

    Hi,
    I am writing an applet that uploads a file to a servlet. I can send the file to the servlet just fine.
    Applet Side
    1. open a URLConnection
    2. open a DataOutputStream
    3. write the file to the DataOutputStream
    Servlet Side:
    1. open a ServletInputStream from the HttpServletRequest
    2. write the bytes to a file
    This is all fine.
    However, I need to upload the filename (a String) with the file. How do I do this? I can't send the filename over as a String from the applet using the same DataOutputStream. right? This would corrupt the file that i am sending as the servlet wouldn't know that the difference between the filename and the actual contents of the file.
    Is there some property I can set in the urlconnection that gets passed to the request variable? i.e. URLConnection.setProperty ("filename", foo.txt) and then on the servlet side do this: String filename = eq.getProperty ("filename")
    Thank you for the help

    If all the additional data you want to send to server are textual or numaric data about the file (which is in the body of the request)
    Use those information as additional http headers.
    And read those header information from the servlet request object at the server side
    ex:-
    URL u = new URL("your url");
    HttpURLConnection c = (HttpURLConnection)u.openConnection();
    c.addRequestProperty("x-application-file-name","name of the file");
    c.addRequestProperty("x-application-file-size","size of the file");
    //then open the stream and write the data to the request body
    //             At server side         //
    String name = request.getHeader("x-application-file-name");
    long size= Long.parseLong(request.getHeader("x-application-file-size"));

  • Uploading large files from applet to servlet throws out of memory error

    I have a java applet that needs to upload files from a client machine
    to a web server using a servlet. the problem i am having is that in
    the current scheme, files larger than 17-20MB throw an out of memory
    error. is there any way we can get around this problem? i will post
    the client and server side code for reference.
    Client Side Code:
    import java.io.*;
    import java.net.*;
    // this class is a client that enables transfer of files from client
    // to server. This client connects to a servlet running on the server
    // and transmits the file.
    public class fileTransferClient
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    // this method transfers the prescribed file to the server.
    // if the destination directory is "", it transfers the file to
    "d:\\".
    //11-21-02 Changes : This method now has a new parameter that
    references the item
    //that is being transferred in the import list.
    public static String transferFile(String srcFileName, String
    destFileName,
    String destDir, int itemID)
    if (destDir.equals(""))
    destDir = "E:\\FTP\\incoming\\";
    // get the fully qualified filename and the mere filename.
    String fqfn = srcFileName;
    String fname =
    fqfn.substring(fqfn.lastIndexOf(File.separator)+1);
    try
    //importTable importer = jbInit.getImportTable();
    // create the file to be uploaded and a connection to
    servlet.
    File fileToUpload = new File(fqfn);
    long fileSize = fileToUpload.length();
    // get last mod of this file.
    // The last mod is sent to the servlet as a header.
    long lastMod = fileToUpload.lastModified();
    String strLastMod = String.valueOf(lastMod);
    URL serverURL = new URL(webadminApplet.strServletURL);
    URLConnection serverCon = serverURL.openConnection();
    // a bunch of connection setup related things.
    serverCon.setDoInput(true);
    serverCon.setDoOutput(true);
    // Don't use a cached version of URL connection.
    serverCon.setUseCaches (false);
    serverCon.setDefaultUseCaches (false);
    // set headers and their values.
    serverCon.setRequestProperty("Content-Type",
    "application/octet-stream");
    serverCon.setRequestProperty("Content-Length",
    Long.toString(fileToUpload.length()));
    serverCon.setRequestProperty(FILENAME_HEADER, destDir +
    destFileName);
    serverCon.setRequestProperty(FILELASTMOD_HEADER, strLastMod);
    if (webadminApplet.DEBUG) System.out.println("Connection with
    FTP server established");
    // create file stream and write stream to write file data.
    FileInputStream fis = new FileInputStream(fileToUpload);
    OutputStream os = serverCon.getOutputStream();
    try
    // transfer the file in 4K chunks.
    byte[] buffer = new byte[4096];
    long byteCnt = 0;
    //long percent = 0;
    int newPercent = 0;
    int oldPercent = 0;
    while (true)
    int bytes = fis.read(buffer);
    byteCnt += bytes;
    //11-21-02 :
    //If itemID is greater than -1 this is an import file
    transfer
    //otherwise this is a header graphic file transfer.
    if (itemID > -1)
    newPercent = (int) ((double) byteCnt/ (double)
    fileSize * 100.0);
    int diff = newPercent - oldPercent;
    if (newPercent == 0 || diff >= 20)
    oldPercent = newPercent;
    jbInit.getImportTable().displayFileTransferStatus
    (itemID,
    newPercent);
    if (bytes < 0) break;
    os.write(buffer, 0, bytes);
    os.flush();
    if (webadminApplet.DEBUG) System.out.println("No of bytes
    sent: " + byteCnt);
    finally
    // close related streams.
    os.close();
    fis.close();
    if (webadminApplet.DEBUG) System.out.println("File
    Transmission complete");
    // find out what the servlet has got to say in response.
    BufferedReader reader = new BufferedReader(
    new
    InputStreamReader(serverCon.getInputStream()));
    try
    String line;
    while ((line = reader.readLine()) != null)
    if (webadminApplet.DEBUG) System.out.println(line);
    finally
    // close the reader stream from servlet.
    reader.close();
    } // end of the big try block.
    catch (Exception e)
    System.out.println("Exception during file transfer:\n" + e);
    e.printStackTrace();
    return("FTP failed. See Java Console for Errors.");
    } // end of catch block.
    return("File: " + fname + " successfully transferred.");
    } // end of method transferFile().
    } // end of class fileTransferClient
    Server side code:
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.util.*;
    import java.net.*;
    // This servlet class acts as an FTP server to enable transfer of
    files
    // from client side.
    public class FtpServerServlet extends HttpServlet
    String ftpDir = "D:\\pub\\FTP\\";
    private static final String FILENAME_HEADER = "fileName";
    private static final String FILELASTMOD_HEADER = "fileLastMod";
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException,
    IOException
    doPost(req, resp);
    public void doPost(HttpServletRequest req, HttpServletResponse
    resp)
    throws ServletException,
    IOException
    // ### for now enable overwrite by default.
    boolean overwrite = true;
    // get the fileName for this transmission.
    String fileName = req.getHeader(FILENAME_HEADER);
    // also get the last mod of this file.
    String strLastMod = req.getHeader(FILELASTMOD_HEADER);
    String message = "Filename: " + fileName + " saved
    successfully.";
    int status = HttpServletResponse.SC_OK;
    System.out.println("fileName from client: " + fileName);
    // if filename is not specified, complain.
    if (fileName == null)
    message = "Filename not specified";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // open the file stream for the file about to be transferred.
    File uploadedFile = new File(fileName);
    // check if file already exists - and overwrite if necessary.
    if (uploadedFile.exists())
    if (overwrite)
    // delete the file.
    uploadedFile.delete();
    // ensure the directory is writable - and a new file may be
    created.
    if (!uploadedFile.createNewFile())
    message = "Unable to create file on server. FTP failed.";
    status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
    else
    // get the necessary streams for file creation.
    FileOutputStream fos = new FileOutputStream(uploadedFile);
    InputStream is = req.getInputStream();
    try
    // create a buffer. 4K!
    byte[] buffer = new byte[4096];
    // read from input stream and write to file stream.
    int byteCnt = 0;
    while (true)
    int bytes = is.read(buffer);
    if (bytes < 0) break;
    byteCnt += bytes;
    // System.out.println(buffer);
    fos.write(buffer, 0, bytes);
    // flush the stream.
    fos.flush();
    } // end of try block.
    finally
    is.close();
    fos.close();
    // set last mod date for this file.
    uploadedFile.setLastModified((new
    Long(strLastMod)).longValue());
    } // end of finally block.
    } // end - the new file may be created on server.
    } // end - we have a valid filename.
    // set response headers.
    resp.setContentType("text/plain");
    resp.setStatus(status);
    if (status != HttpServletResponse.SC_OK)
    getServletContext().log("ERROR: " + message);
    // get output stream.
    PrintWriter out = resp.getWriter();
    out.println(message);
    } // end of doPost().
    } // end of class FtpServerServlet

    OK - the problem you describe is definitely what's giving you grief.
    The workaround is to use a socket connection and send your own request headers, with the content length filled in. You may have to multi-part mime encode the stream on its way out as well (I'm not about that...).
    You can use the following:
    http://porsche.cis.udel.edu:8080/cis479/lectures/slides-04/slide-02.html
    on your server to get a feel for the format that the request headers need to take.
    - Kevin
    I get the out of Memory Error on the client side. I
    was told that this might be a bug in the URLConnection
    class implementation that basically it wont know the
    content length until all the data has been written to
    the output stream, so it uses an in memory buffer to
    store the data which basically causes memory issues..
    do you think there might be a workaround of any kind..
    or maybe a way that the buffer might be flushed after
    a certain size of file has been uploaded.. ?? do you
    have any ideas?

  • Writing Image files from Applet to Servlet

    How to write ImageFiles from an Applet to a Servlet?
    I draw a image on a JComponent in Applet and wanted to save the image file in the server.
    I am unable to write an Image Object to the Servlet as the BufferedImage class is not serialized.
    I tried writing the image to the Servlet output stream and tried reading the data in the servlet and writing the data to a jpg file.
    But the files is not being written as proper jpeg file.
    Any help would be great.
    Thanks,
    Sridhar.

    I get the following exception below when i try to write a Serialized object from an applet to the servlet.
    I copied the serialized class jar file to the tomcat webserver lib folder.
    The serialized class has a BufferedImage object.
    Serialized Class Code
    public class SerializedImage implements Serializable{
         private BufferedImage im = null;
         public SerializedImage() {
              super();
         public BufferedImage getSerializedObject() {
              return im;
         public void setSerializedObject((BufferedImage im) {
              this.im = im;
         private BufferedImage fromByteArray(byte[] imagebytes) {
              try {
                   if (imagebytes != null && (imagebytes.length > 0)) {
                        BufferedImage im = ImageIO.read(new ByteArrayInputStream(imagebytes));
                        return im;
                   return null;
              } catch (IOException e) {
                   throw new IllegalArgumentException(e.toString());
         private byte[] toByteArray(BufferedImage o) {
              if(o != null) {
                   BufferedImage image = (BufferedImage)o;
                   ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
                   try {
                        ImageIO.write(image, "jpg", baos);
                   } catch (IOException e) {
                        throw new IllegalStateException(e.toString());
                   byte[] b = baos.toByteArray();
                   return b;
              return new byte[0];
         private void writeObject(java.io.ObjectOutputStream out)
         throws IOException {
              byte[] b = toByteArray(im);
              out.writeInt(b.length);
              out.write(b);
         private void readObject(java.io.ObjectInputStream in)
         throws IOException, ClassNotFoundException {
              int length = in.readInt();
              byte[] b = new byte[length];
              in.read(b);
              im = fromByteArray(b);
    Exception :
    java.io.StreamCorruptedException: unexpected block data
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1288)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:18
    45)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1769)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1
    646)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1274)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:324)
    Is there any thing that i am missing or doing wrong?
    Thanks,
    Sridhar.

  • How to transfer the http request from applet to servlet/jsp

    I use the JTree component to create a navigation of a website,but i don't
    know how to connect the tree's nodes with the jsp/servlet.
    I mean how to transfer the http request from the applet to a jsp.
    I use the "<frameset>" mark which will divide the web browse into 2 blocks.
    The left side is Applet,and the right side is the linked jsp page.
    what I say is as the weblogic console layout.
    who can help me!!!
    Thank You!

    I use the JTree component to create a navigation of a website,but i don't
    know how to connect the tree's nodes with the jsp/servlet.
    I mean how to transfer the http request from the applet to a jsp.
    I use the "<frameset>" mark which will divide the web browse into 2 blocks.
    The left side is Applet,and the right side is the linked jsp page.
    what I say is as the weblogic console layout.
    who can help me!!!
    Thank You!

  • Passing Parameter from javascript to Servlet

    hi,
    I have 2 list boxes in my Jsp page and values for these list boxes are preloaded . These things are to be carried out using javascript onload() function.
    So now i want to pass the selected parameters from both the list boxes to servlet and have to display the corresponding resulting datas in same JSP page. if i submit the form then values selelcted by the user will reset because the form has onload() function. then i thought hidden field will solve my problem. but its giving error like nullpointer exception.
    so please tell me how to achive this.

    When you right a new Option(...) line in javascript, there are three parameters you can give:
    Option("text", "value", selected);
    How you make use of this depends on how you move from the servlet back to the JSP.
    So for example, if you are doing a response.sendRedirect in the servlet, you will either have to add a parameter back to the url you are re-directing to, or add the value to the session. (I like the session method myself... hides it from the user)
    //in servlet
      public void doGet(...)... {
        String country = request.getParameter("country");
        String state = request.getParameter("state");
        //... Do Stuff ...
        HttpSession session session = request.getSession();
        session.setAttribute("country", country);
        session.setAttribute("state", state);
        String sendTo = response.encodeRedirectURL("theForm.jsp");
        response.sendRedirect(sendTo);
      //... The JSP might look like this now...
      //Get the selected values from the session:
      <%
        String countrySelected = (String)session.getAttribute("country");
        String stateSelected = (String)session.getAttribute("state");
      %>
      <html>
      <head>
      <script type="text/javascript">
      /* Use this to store the values for states in JavaScript */
      var state2DArray;
      /* Javascript function to set up values for the states  and countries */
      function initSelects() {
        <%
          /* This is JSP scriptlet code to get the country list that we need... */
          List countries = (List)application.getAttribute("countryList");
        %>
        countrySelect = document.form.country;
        <%
          /* This is JSP scriptlet code to loop through the countries and assign
           * values as needed.  We will break out of scriptlets to print out
           * the javascript needed to assign values to the countrySelect and to
           * the state2DArray
          int countryCount = countries.size();
        %>
        state2DArray=new Array(<%=countryCount+1%>);
          state2DArray[0] = new Array(1);
          state2DArray[0][0]="--Select A State--";
        <%
          for (int co = 1; co <= countryCount; co++) {
            Country country = (Country)countries.get(co-1);
            List stateList = country.getStates();
            int stateCount = stateList.size();
        %>
        //Now we add a true/false if the country should be selected...
        countrySelect.options[<%=co%>] = new Option("<%=country.getName()%>","<%=country.getId()%>",
                                                    <%= (country.getId() == countrySelected)%>);
        state2DArray[<%=co%>] = new Array(<%=stateCount+1%>);
        state2DArray[<%=co%>][0] = "--Select A State--";
        <%
            for (int st = 1; st <= stateCount; st++) {
              String stateName = (String)stateList.get(st-1);
        %>
        state2DArray[<%=co%>][<%=st%>] = "<%=stateName%>";
        //We are going to call the fillInStates now at the end of initSelects so the initial
        //values are passed on to the states...
        fillInStates(countrySelect);
        <%
        %>
      function fillInStates(countrySelect) {
        selectedCountry = countrySelect.selectedIndex;
        stateCount = state2DArray[selectedCountry].length;
        stateSelect = document.form.state;
        stateSelect.options.length = 0;
        for (state = 0; state < stateCount; state++) {
          //Again add true/false if it should be selected...
          stateSelect.options[state] = new Option(state2DArray[selectedCountry][state], state2DArray[selectedCountry][state],
                                                  <%= (stateSelected == state2DArray[selectedCountry][state]) %>);
    </script>
      </head>
      <body onload="initSelects()">
      <form name="form" id="form" action="#" method="get">
        <select name="country" id="country" onchange="fillInStates(this);">
          <option value="">--Select A Country--</option>
        </select>
        <select name="state" id="state">
          <option value="">--Select a State--</option>
        </select>
      </form>
      </body>
    </html>

  • Passing parameter from applet to portal is failing

    hi all.
    We have an external applet that we can view on the portal. We want to have two parameter (parm1 and parm2) passed from the applet to the gateway and thus have them re-written by the portal gateway.
    When we access the applet from the portal, and View Source inside the browser's window, we see that the gateway URL does not precede the parameter's url:
    we see:
    <PARAM NAME = "param1" VALUE="http://host.domain.com:8080/JUPL/...
    instead of:
    <PARAM NAME = "param1" VALUE="https://http://host.domain.com/http://host.domain.com:8080/JUPL/...
    However, we are following sun docs on how to apply rules for HTML content (As in http://docs.sun.com/source/816-6359-10/rewrtadm.html#23362).
    here's our rule:
         <Applet source="*/applet1.jsp" code="java2.applet1.client.MApplet.class"
         param="param1;param2;"/>
    Any ideas on how to solve this?
    Thanks!

    Here this shold work for ya
    you just have to add a extra text file or what ever but this will give you some ideas
      import java.awt.*;
    import java.net.*;
    import java.awt.event.*;
    import java.applet.*;
    import javax.swing.*;
    public class a extends Applet implements ActionListener {
    Button button = new Button("click");
    TextField field = new TextField(20);
    JFrame frame = new JFrame();
      String gg;
    public void init() {
      add(button);
       add(field);
       button.addActionListener(this);
    public void actionPerformed(ActionEvent eve) {
           if(eve.getSource() == button) {
                try{
                         gg = field.getText();
                     JOptionPane.showMessageDialog(frame, gg);
               } catch(Exception e) {}
    }hope this helps

  • Why passing string from applet to jsp doesn't work?

    Hi,all:
    I have a application requires applet to get client side info, then pass this "info"--string to the JSP.
    Applet code:
    try{
         URL url = new URL(getCodeBase(),"test.jsp?
    java.version=1.2.2&java.vendor=Sun);
         URLConnection conn = url.openConnection();
         conn.setDoOutput(true);
         conn.setUseCaches(false);
         conn.setRequestProperty("Content-Type", "application/octet-stream");
         conn.connect();
    } catch (Exception e) {
         System.out.println("The error is at URL:"+e.getMessage());
    My jsp code is:
    <%
    String java_version=request.getParameter("java.version");
    String java_vendor=request.getParameter("java.vendor");
    %>
    However, it doesn't work. Could anybody help me figure out?
    Thanks in advance.
    Paul

    Request Jsp with
    test.jsp?URLEncoder.encode("java.version")=URLEncoder.encode("java.version.value")&URLEncoder.encode("java.vendor")=
    URLEncoder.encode("java.vendor.value")

Maybe you are looking for

  • Can i move songs from my iPod to my new matchbook air?

    I bought a brand new mackbook air and i had trouble on the migration assisstant because the verification window wouldnt show up on my old dell. I would now like to know if i am able to move songs from my ipod to my new mac without having to use migra

  • Apple ID creation issue

    I'm creating a new Apple ID for a new device, i don't want to use my main ID. I went to settings, create new ID and all, but i can't get past the billing info page. I put the credit car info and all, but i get a little "error". No field is marked in

  • Javascrip call sqldatasource select with parameters

    It is possible call sqldatasource select with setting parameters in javascript function?

  • Optimal Settings for FCP6 on MacBook Pro?

    Up until a week ago, I've worked mostly on a Mac Pro with Final Cut Studio 2. I've been fortunate enough to get a MacBook Pro (2.6Ghz) also outfitted with FCS2 and I'm wondering if there is such a thing as "optimal settings" for running FCS2 on the p

  • Why can't I see the icons on my toolbar on my desktop

    I backed up my computer because my startup disk was full, and now I can't see the icons on the top toolbar on my desktop, the icons for (send, trash etc) in Mail and the icons in the Safari App.  I have deleted things to empty the computer but this i