You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@tomcat.apache.org by Teh Noranis Mohd Aris <te...@yahoo.com> on 2007/03/02 05:33:52 UTC

File Content Not Saved To Server

Dear All, 
   
  I want to save a file name and its content to the computer server at directory C:/temp/. I've passed the file name and file content parameter from the applet to the servlet. The problem now is that the file name is created in the computer server directory but a 'null' is included in the file content. Can anyone please help me solve the problem why this is happening? 
  Thank you so much.
   
  The applet is as follows:
   
  // AppletSave.java
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JApplet;
import javax.swing.text.BadLocationException;
import java.net.*;
import java.io.*;
import java.util.*;
  public class AppletSave extends JApplet implements ItemListener, ActionListener
{
 
 JPanel panel1, panellabel, panelbutton, paneltext;
 
 JTextField namefile;
 
 JButton jbtSave;
 
 JTextArea textEditor;
 
 JLabel labelfile;
 
 public void init() 
 {
  
  Container container = getContentPane();
   
  namefile = new JTextField(10);
  
  panel1 = new JPanel();
  
  panellabel = new JPanel();
  panelbutton = new JPanel();
  paneltext = new JPanel();
  
  labelfile = new JLabel("File Name");
 
  panellabel.setLayout(new FlowLayout(FlowLayout.LEFT,50,0));
  panellabel.add(labelfile);
  panellabel.add(namefile);
     
  panelbutton.setLayout(new GridLayout(1,1));
  
  panelbutton.add(jbtSave = new JButton("Save"));
  
  textEditor = new JTextArea(18,63);
        textEditor.setFont(new Font("monospaced",Font.PLAIN,12));
        JScrollPane scrollPane1 = new JScrollPane(textEditor);
        Linenumber linenumber1 = new Linenumber ( textEditor );
        scrollPane1.setRowHeaderView(linenumber1);
        paneltext.add(scrollPane1);
               
  panel1.add(panellabel);
  panel1.add(paneltext);
  panel1.add(panelbutton);
 
  container.add(panel1);
  
  jbtSave.addActionListener (
     new ActionListener() {
      public void actionPerformed (ActionEvent en) {
       savefile();
      }
     }
     );
   
    } // end init
 
  public void actionPerformed(ActionEvent ae) 
  {
   
  } // End action perform 
  
  public void itemStateChanged(ItemEvent ie) 
  {
   
  } // End item state changed
  
  
  public void savefile()
  { 
  
 String filename = namefile.getText();    
 String teditor = textEditor.getText();             
   URL servletUrl = null;
 
 URLConnection con;
 
 String servletName = "http://localhost:8080/examples/servlet/ServletIde";
   try
 {
  servletUrl = new URL(servletName + "?filename="+filename+"&teditor="+teditor);
  con = servletUrl.openConnection();
  con.setUseCaches(false);
 
  BufferedReader buf = new BufferedReader(new InputStreamReader(con.getInputStream()));
 }
 
 catch(Exception e)
 {
  System.out.println("Exception caught..."+e);
 }
            
   } // end savefile
  } // end class AppletSave
   
  The servlet is as follows:
   
  import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
  public class ServletSave extends HttpServlet {
 
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
 {
  
  HttpSession session = req.getSession();
  PrintWriter out = res.getWriter();
  
  out.println("<html>");
  out.println("<head>");
  out.println("<title>Login</title>");
  out.println("<center><h2>Save File To Server</h2>");
  out.println("<applet width=500 height=400");
  out.println("name=\"AppletSave\"");
  out.println("codebase=\"/\"");
  out.println("code=\"AppletSave\">");
  out.println("<param name=\"servlet\" value=\"" +
              req.getRequestURI() + "\">");
  out.println("<param name=\"id\" value=\"" +
              session.getId() + "\">");
  out.println("</applet>");
  out.println("</center></body></html>"); 
     
     
     String name = req.getParameter("filename");
     String content = req.getParameter("teditor");
         
     String nameFile = "C:/temp/"+name;
     FileWriter resultsFile = new FileWriter(nameFile,true);
     PrintWriter toFile = new PrintWriter(resultsFile,true);
     toFile.println(content);
     toFile.close();                   
 }
 
} 
   
  Yours Sincerely,
  TEH NORANIS

 
---------------------------------
The fish are biting.
 Get more visitors on your site using Yahoo! Search Marketing.

Re: File Content Not Saved To Server

Posted by or...@kewlstuff.co.za.

Its been a really long time since I played with Applets, but if I remember 
correctly I think you screwed. I dont think an applet container will let you 
access a local file system and send it to a server, it would create huge 
security holes. So even if you get the code right, browser will start 
outputtung security exceptions.... if I understand correctly, cant actually 
make out how you accessing the local file.

I think you gonna have to use a file uploader... theres one on the apache 
site.
My general comment is that in general Java Applets are dead.... microsoft 
saw to that.

If the user has Java on their machine and you really really have to have a 
Swing type app.... then another way is to
maybe use http://coolese.100free.com/
I have a free application server... easy to use, you can let them run the 
Swing application FROM the server.
I think they would still have to pull a very small App from the browser, but 
it will start very quick.
I think as soon as you try run any local disk access from an Applet.... you 
outta luck.





----- Original Message ----- 
From: "Teh Noranis Mohd Aris" <te...@yahoo.com>
To: "Tomcat Users List" <us...@tomcat.apache.org>
Sent: Monday, March 12, 2007 5:10 AM
Subject: Re: File Content Not Saved To Server


> Dear All,
>
>  I really need this program to work as soon as possible and need urgent 
> help! Mr. Christopher Schultz have given suggestions on how to solve the 
> problem and I've tried his suggestions. Thank you so much, as half of the 
> problem have been solved. I've created 3 files as suggested: 
> SaveFileApplet.java, SaveFileApplet.html and SaveFileServlet.java. This 
> solves the problem of the creation of a null file by the system. Now, a 
> file name that was input by the user was created BUT the problem is that, 
> when I open the file, the word "null" was written to the file NOT the file 
> content. The filename parameter was sent from the applet to the servlet 
> BUT the file content parameter was not sent. This means that the file 
> content parameter does not exist and the servlet did not receive the file 
> content parameter! Did I pass the file content correctly from 
> SaveFileApplet.java and did the SaveFileServlet receive the parameter 
> using req.getParameter("teditor");? I'm attaching the 3 files
> (errer-free) as I mentioned. I really really hope that anyone can help me 
> solve this problem. Thank you so much.
>
>  FIRST FILE: SaveFileApplet.java
>
>  // C:\jakarta-tomcat-4.1.31\webapps\ROOT\SaveFileApplet.java
>
>  import java.awt.*;
> import java.awt.event.*;
> import javax.swing.*;
> import javax.swing.JApplet;
> import javax.swing.text.BadLocationException;
> import java.net.*;
> import java.io.*;
> import java.util.*;
>
>  public class SaveFileApplet extends JApplet implements ItemListener, 
> ActionListener
> {
>
> JPanel panel1, panellabel, panelbutton, paneltext;
> JTextField namefile;
> JButton jbtSave;
> JTextArea textEditor;
> JLabel labelfile;
> public void init()
> {
>
>  Container container = getContentPane();
>  namefile = new JTextField(10);
>  panel1 = new JPanel();
>  panellabel = new JPanel();
>  panelbutton = new JPanel();
>  paneltext = new JPanel();
>
>  labelfile = new JLabel("File Name");
>
>  panellabel.setLayout(new FlowLayout(FlowLayout.LEFT,50,0));
>  panellabel.add(labelfile);
>  panellabel.add(namefile);
>
>  panelbutton.setLayout(new GridLayout(1,1));
>  panelbutton.add(jbtSave = new JButton("Save"));
>
>  textEditor = new JTextArea(18,63);
>  textEditor.setFont(new Font("monospaced",Font.PLAIN,12));
>  JScrollPane scrollPane1 = new JScrollPane(textEditor);
>  Linenumber linenumber1 = new Linenumber ( textEditor );
>  scrollPane1.setRowHeaderView(linenumber1);
>  paneltext.add(scrollPane1);
>
>  panel1.add(panellabel);
>  panel1.add(paneltext);
>  panel1.add(panelbutton);
>  container.add(panel1);
>
>  jbtSave.addActionListener (
>     new ActionListener() {
>      public void actionPerformed (ActionEvent en) {
>       savefile();
>      }
>     }
>     );
>
>    } // end init
>
>  public void actionPerformed(ActionEvent ae)
>  {
>
>  } // End action perform
>
>  public void itemStateChanged(ItemEvent ie)
>  {
>
>  } // End item state changed
>
>  public void savefile()
>  {
>
>    String filename = namefile.getText();
>    String teditor = textEditor.getText();
>      URL servletUrl = null;
>    URLConnection con;
>
>    String servletName = 
> http://localhost:8080/examples/servlet/SaveFileServlet;
>   try
> {
>  servletUrl = new URL(servletName + "?filename=" + filename);
>  con = servletUrl.openConnection();
>  con.setDoOutput(true);
>  con.connect();
>
>  ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
>  DataOutputStream out = new DataOutputStream(byteOut);
>  out.writeUTF(teditor);
>  out.flush();
>  out.close();
>
>  DataInputStream in = new DataInputStream(con.getInputStream());
>  in.close();
> }
>
> catch(Exception e)
> {
>  System.out.println("Exception caught..."+e);
> }
> } // end savefile
>  } // end class SaveFileApplet
>
>  SECOND FILE: SaveFile Applet.html
>
>  <html>
> <head>
> <title>save file</title>
> </head>
> <body BGCOLOR=WHITE>
> <div align="center">
> <table WIDTH="70%" align="center">
> <tr align="center" bgcolor="#CCC66H"><td><< SAVE FILE >></td></tr>
> <tr align="center">
> <td>
> <applet CODE="SaveFileApplet.class" WIDTH=500 HEIGHT=400>
> </applet>
> </td>
> </tr>
> </table>
> </div>
> </body>
> </html>
>
>  THIRD FILE: SaveFileServlet.java
>
>  // 
> C:\jakarta-tomcat-4.1.31\webapps\examples\WEB-INF\classes\SaveFileServlet.java
>
>  import java.io.*;
> import java.text.*;
> import java.util.*;
> import javax.servlet.*;
> import javax.servlet.http.*;
>
>  public class SaveFileServlet extends HttpServlet {
>
> public void doGet(HttpServletRequest req, HttpServletResponse res) throws 
> IOException, ServletException
> {
>     String name = req.getParameter("filename");
>     String content = req.getParameter("teditor");
>
>     String nameFile = "C:/temp/"+name;
>
>     FileWriter resultsFile = new FileWriter(nameFile,true);
>     PrintWriter toFile = new PrintWriter(resultsFile,true);
>
>     toFile.println(content);
>     toFile.close();
> }
> }
>
>  Yours Sincerely,
>  TEH NORANIS
>
> Teh Noranis Mohd Aris <te...@yahoo.com> wrote:
>  Dear All,
>
> Thank you so much for the explanation, Mr. Christopher Schultz. I 
> understand that by just using a "file" input type, I can upload a file 
> directly. In fact, I already construct the program and it is already 
> working. However, I choose to use applet to get the advantage of Java GUI 
> programming, which is event-driven. Actually, the save file module is only 
> part of the system. I'm going to try what has been suggested and I will 
> get to you soon. Thank you so much.
>
> Yours Sincerely,
> TEH NORANIS
>
> Christopher Schultz wrote:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
>
> Teh,
>
> Teh Noranis Mohd Aris wrote:
>> In
>> my program, I want the servlet to load an applet where I can input
>> the file name in a given text field and the file content in a given
>> text area.
>
> Just out of curiosity, why do you want an applet to do this when you can
> just use a "file" input type and upload a file directly?
>
>> When the user has input the information, I want to POST
>> the file name and its content from the applet to the servlet.
>
> You are not using a POST. You are using a GET. If you want to use a
> POST, you will have to write your file content to the request body,
> instead of putting it into a URL parameter.
>
> You had something like this:
>
> String url = "http://.../servlet?filename=[name]&content=[contents]";
>
> URLConnection conn = new URL(url).openConnection();
> conn.connect();
> conn.close();
>
> Instead, you should do something like this:
>
> String url = "http://...servlet?filename=[name]";
> URLConnection conn = new URL(url).openConnection();
> conn.setDoOutput(true);
> conn.setHeader("Content-Length", contents.length());
> conn.connect();
>
> OutputStream out = conn.getOutputStream();
> out.write(contents);
> out.flush();
> out.close();
>
> conn.close();
>
> This will put the contents of your file into the request body, instead
> of in the URL parameters.
>
>> I do not know whether I pass the
>> parameters from the applet to the servlet correctly.
>
> To check that the parameters are correct, put something like this into
> your servlet code:
>
> System.out.println("param[filename] = "
> + request.getParameter("filename"));
>
> Also, you might want to print out the fill path of the file you are
> trying to create. This really ought to do it:
>
> File target = new File("C:\\TEMP", filename);
>
> FileOutputStream out = new FileOutputStream(target);
> out.write(contents);
> out.flush();
> out.close();
>
>> After I input
>> the file name and the file content, 2 files were created by the
>> system: 1. a file with the name null 2. a source code file with a
>> file name from the user input with no content at all.
>
> I'm not sure how that extra file is being created. Your code only had a
> single "open" call. Is it possible that "null" was created from an old
> copy of the code, and you just forgot to delete the file?
>
> Finally, don't use a FileWriter unless you know that you are dealing
> with text. Otherwise, binary files will be corrupted. I'm not sure if
> that matters to you, but creating a servlet that handles any type of
> file will be more useful than one that only handles text.
>
>> Yes, I'm using
>> the same servlet to save a file and serving a page to save files.
>> What is actually the matter with that approach?
>
> It just seems that the "save file" servlet should do nothing but save a
> file. Why have this servlet return any content at all? If I were writing
> this "system", I would have the following files:
>
> applet.html (contains element to serve the applet)
> SaveFileServlet (saves files, as discussed)
>
> When you want to display the applet, just display applet.html.
> Otherwise, your SaveFileServlet will write to a file called "null" every
> time you try to display the page (that's probably where your "null" file
> is coming from).
>
> Only call the SaveFileServlet when you actually want to save data.
>
> - -chris
> -----BEGIN PGP SIGNATURE-----
> Version: GnuPG v1.4.6 (MingW32)
> Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org
>
> iD8DBQFF6b3n9CaO5/Lv0PARApg9AKCHsXSGif7v69laYl4u1DHmGvRrHACbB7cz
> z2uU32oMdoJKcvL1/9EXf6A=
> =sF79
> -----END PGP SIGNATURE-----
>
> ---------------------------------------------------------------------
> To start a new topic, e-mail: users@tomcat.apache.org
> To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
> For additional commands, e-mail: users-help@tomcat.apache.org
>
>
>
>
> ---------------------------------
> Never miss an email again!
> Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out.
>
>
> ---------------------------------
> TV dinner still cooling?
> Check out "Tonight's Picks" on Yahoo! TV. 


---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Re: File Content Not Saved To Server

Posted by Teh Noranis Mohd Aris <te...@yahoo.com>.
Dear All,
   
  I've already modified my program based on Mr. Christopher's solution but thers's still the word "null" in the file. 
   
  You probably have a null content variable. String.valueOf(null) returns
"null", so that's probably what's happening.

  I only declared URL servletUrl = null but now I already commented it.  

  For your information, the purpose of my program is ONLY to save information from the client to the server. I don't intend to send back information from the server to the client.  
   
  My complete program looks like this now after the suggested modification (ClientIdea.java, ServerIdea.java, ClientIdea.html not included):
   
  // C:\jakarta-tomcat-4.1.31\webapps\ROOT\ClientIdea.java
  import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JApplet;
import javax.swing.text.BadLocationException;
import java.net.*;
import java.io.*;
import java.util.*;
   
  public class ClientIdea extends JApplet implements ItemListener, ActionListener
{
 
 JPanel panel1, panellabel, panelbutton, paneltext;
 JTextField namefile;
 JButton jbtSave;
 JTextArea textEditor;
 JLabel labelfile;
 
 public void init() 
 {
  
  Container container = getContentPane();
  namefile = new JTextField(10);
  panel1 = new JPanel();
  
  panellabel = new JPanel();
  panelbutton = new JPanel();
  paneltext = new JPanel();
  
  labelfile = new JLabel("File Name");
 
  panellabel.setLayout(new FlowLayout(FlowLayout.LEFT,50,0));
  panellabel.add(labelfile);
  panellabel.add(namefile);
     
  panelbutton.setLayout(new GridLayout(1,1));
  panelbutton.add(jbtSave = new JButton("Save"));
         
  textEditor = new JTextArea(18,63);
        textEditor.setFont(new Font("monospaced",Font.PLAIN,12));
        JScrollPane scrollPane1 = new JScrollPane(textEditor);
        Linenumber linenumber1 = new Linenumber ( textEditor );
        scrollPane1.setRowHeaderView(linenumber1);
        paneltext.add(scrollPane1);
      
  panel1.add(panellabel);
  panel1.add(paneltext);
  panel1.add(panelbutton);
 
  container.add(panel1);
  
  jbtSave.addActionListener (
     new ActionListener() {
      public void actionPerformed (ActionEvent en) {
       savefile();
      }
     }
     );
   
    } // end init
 
  public void actionPerformed(ActionEvent ae) 
  {
   
  } // End action perform 
  
  public void itemStateChanged(ItemEvent ie) 
  {
   
  } // End item state changed
  
  
  public void savefile()
  { 
    String filename = namefile.getText();    
    String teditor = textEditor.getText();
   
  //URL servletUrl = null;
 
 URL servletUrl;
 
 URLConnection con;
 
 String servletName = http://localhost:8080/examples/servlet/ServerIdea;
   try
 {
  servletUrl = new URL(servletName + "?filename=" + filename);
  con = servletUrl.openConnection();
  con.setDoOutput(true);
  con.setRequestProperty("Content-Type","text/plain;charset=UTF-8");
  con.connect();
     
  OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream(),"UTF-8"); 
  out.write(teditor, 0, teditor.length());
  out.flush();
  out.close();
  
  DataInputStream in = new DataInputStream(con.getInputStream());
  in.close();
 }
 
 catch(Exception e)
 {
  System.out.println("Exception caught..."+e);
 }
            
   } // end savefile
  } // end class ClientIdea
   
  // C:\jakarta-tomcat-4.1.31\webapps\examples\WEB-INF\classes\ServletIdea.java
  import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
   
  public class ServerIdea extends HttpServlet {
 
 public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
 {   
     String name = req.getParameter("filename");
     String content = req.getParameter("teditor");
            
     PrintWriter outFile = new PrintWriter(new OutputStreamWriter(new FileOutputStream("C:/temp/"+name)));
     outFile.println(content);
     outFile.close();
 }
 
 public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
         doGet(req, res);
    }  
}
   
  Did I miss out anything? Please help me! Thank you.
   
  Yours Sincerely,
  TEH NORANIS
  
Christopher Schultz <ch...@christopherschultz.net> wrote:
  -----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> Now, a file name that was input by the user
> was created BUT the problem is that, when I open the file, the word
> "null" was written to the file NOT the file content.

You probably have a null content variable. String.valueOf(null) returns
"null", so that's probably what's happening.

> The filename
> parameter was sent from the applet to the servlet BUT the file
> content parameter was not sent.

You're going to want to fix that.

> This means that the file content
> parameter does not exist and the servlet did not receive the file
> content parameter!

Sounds about right. If I were you, I would modify my program to do
nothing if there's no file content parameter. (Well, I would actually
use PUT and place the content in the body of the request, but...).

> servletUrl = new URL(servletName + "?filename=" + filename);
> con = servletUrl.openConnection();
> con.setDoOutput(true);
> con.connect();

So far so good.

> ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
> DataOutputStream out = new DataOutputStream(byteOut);
> out.writeUTF(teditor);
> out.flush();
> out.close();

Uhh... you put your data into a ByteArrayOutputStream and then did
nothing with it at all. You need to write it to the URLConnection's
OutputStream:

If you are going to be using UTF, you need to specify that when
connecting to your server so it knows what character set you are using.
Use the "Content-Type" header for this:

con.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");

DataOutputStream uses "modified" UTF-8, and is actually intended to be
used with Java object serialization. Don't do this. Instead, use real
UTF-8 like this:

Instead of the above, do this:

OutputStreamWriter out
= new OutputStreamWriter(con.getOutputStream(), "UTF-8"));
out.write(teditor, 0, teditor.length());
out.flush();
out.close();

> DataInputStream in = new DataInputStream(con.getInputStream());
> in.close();

To be correct, you ought to empty this inputstream before closing it.

Also, if you ever hope to use non-text data, you should change your
content type to "application/octet-stream" with no encoding at all (the
encoding is basically "raw"). You'll also want to write bytes instead of
Strings to your output stream and get rid of the OutputStreamWriter.

- -chris

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF9WgG9CaO5/Lv0PARAmeOAJ9HpfJPFQxkH2MTUnFn0qWs0MZ/PwCfY1Fj
GvWkPIZAvF8TDKBzPTJ+p2E=
=crVh
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org



 
---------------------------------
It's here! Your new message!
Get new email alerts with the free Yahoo! Toolbar.

Re: File Content Not Saved To Server

Posted by Christopher Schultz <ch...@christopherschultz.net>.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> Now, a file name that was input by the user
> was created BUT the problem is that, when I open the file, the word
> "null" was written to the file NOT the file content.

You probably have a null content variable. String.valueOf(null) returns
"null", so that's probably what's happening.

> The filename
> parameter was sent from the applet to the servlet BUT the file
> content parameter was not sent.

You're going to want to fix that.

> This means that the file content
> parameter does not exist and the servlet did not receive the file
> content parameter!

Sounds about right. If I were you, I would modify my program to do
nothing if there's no file content parameter. (Well, I would actually
use PUT and place the content in the body of the request, but...).

>   servletUrl = new URL(servletName + "?filename=" + filename);
>   con = servletUrl.openConnection();
>   con.setDoOutput(true);
>   con.connect();

So far so good.

>   ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
>   DataOutputStream out = new DataOutputStream(byteOut);
>   out.writeUTF(teditor);
>   out.flush();
>   out.close();

Uhh... you put your data into a ByteArrayOutputStream and then did
nothing with it at all. You need to write it to the URLConnection's
OutputStream:

If you are going to be using UTF, you need to specify that when
connecting to your server so it knows what character set you are using.
Use the "Content-Type" header for this:

con.setRequestProperty("Content-Type", "text/plain; charset=UTF-8");

DataOutputStream uses "modified" UTF-8, and is actually intended to be
used with Java object serialization. Don't do this. Instead, use real
UTF-8 like this:

Instead of the above, do this:

OutputStreamWriter out
   = new OutputStreamWriter(con.getOutputStream(), "UTF-8"));
out.write(teditor, 0, teditor.length());
out.flush();
out.close();

>   DataInputStream in = new DataInputStream(con.getInputStream());
>   in.close();

To be correct, you ought to empty this inputstream before closing it.

Also, if you ever hope to use non-text data, you should change your
content type to "application/octet-stream" with no encoding at all (the
encoding is basically "raw"). You'll also want to write bytes instead of
Strings to your output stream and get rid of the OutputStreamWriter.

- -chris

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.7 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF9WgG9CaO5/Lv0PARAmeOAJ9HpfJPFQxkH2MTUnFn0qWs0MZ/PwCfY1Fj
GvWkPIZAvF8TDKBzPTJ+p2E=
=crVh
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Re: File Content Not Saved To Server

Posted by Teh Noranis Mohd Aris <te...@yahoo.com>.
Dear All,
   
  I really need this program to work as soon as possible and need urgent help! Mr. Christopher Schultz have given suggestions on how to solve the problem and I've tried his suggestions. Thank you so much, as half of the problem have been solved. I've created 3 files as suggested: SaveFileApplet.java, SaveFileApplet.html and SaveFileServlet.java. This solves the problem of the creation of a null file by the system. Now, a file name that was input by the user was created BUT the problem is that, when I open the file, the word "null" was written to the file NOT the file content. The filename parameter was sent from the applet to the servlet BUT the file content parameter was not sent. This means that the file content parameter does not exist and the servlet did not receive the file content parameter! Did I pass the file content correctly from SaveFileApplet.java and did the SaveFileServlet receive the parameter using req.getParameter("teditor");? I'm attaching the 3 files
 (errer-free) as I mentioned. I really really hope that anyone can help me solve this problem. Thank you so much.
   
  FIRST FILE: SaveFileApplet.java
   
  // C:\jakarta-tomcat-4.1.31\webapps\ROOT\SaveFileApplet.java
   
  import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.JApplet;
import javax.swing.text.BadLocationException;
import java.net.*;
import java.io.*;
import java.util.*;
   
  public class SaveFileApplet extends JApplet implements ItemListener, ActionListener
{
 
 JPanel panel1, panellabel, panelbutton, paneltext;
 JTextField namefile;
 JButton jbtSave;
 JTextArea textEditor;
 JLabel labelfile;
 public void init() 
 {
  
  Container container = getContentPane();
  namefile = new JTextField(10);
  panel1 = new JPanel();
  panellabel = new JPanel();
  panelbutton = new JPanel();
  paneltext = new JPanel();
  
  labelfile = new JLabel("File Name");
 
  panellabel.setLayout(new FlowLayout(FlowLayout.LEFT,50,0));
  panellabel.add(labelfile);
  panellabel.add(namefile);
     
  panelbutton.setLayout(new GridLayout(1,1));
  panelbutton.add(jbtSave = new JButton("Save"));
           
  textEditor = new JTextArea(18,63);
  textEditor.setFont(new Font("monospaced",Font.PLAIN,12));
  JScrollPane scrollPane1 = new JScrollPane(textEditor);
  Linenumber linenumber1 = new Linenumber ( textEditor );
  scrollPane1.setRowHeaderView(linenumber1);
  paneltext.add(scrollPane1);
      
  panel1.add(panellabel);
  panel1.add(paneltext);
  panel1.add(panelbutton);
  container.add(panel1);
  
  jbtSave.addActionListener (
     new ActionListener() {
      public void actionPerformed (ActionEvent en) {
       savefile();
      }
     }
     );
   
    } // end init
 
  public void actionPerformed(ActionEvent ae) 
  {
   
  } // End action perform 
  
  public void itemStateChanged(ItemEvent ie) 
  {
   
  } // End item state changed
  
  public void savefile()
  { 
    
    String filename = namefile.getText();    
    String teditor = textEditor.getText();
      URL servletUrl = null;
    URLConnection con;
 
    String servletName = http://localhost:8080/examples/servlet/SaveFileServlet;
   try
 {
  servletUrl = new URL(servletName + "?filename=" + filename);
  con = servletUrl.openConnection();
  con.setDoOutput(true);
  con.connect();
    
  ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
  DataOutputStream out = new DataOutputStream(byteOut);
  out.writeUTF(teditor);
  out.flush();
  out.close();
  
  DataInputStream in = new DataInputStream(con.getInputStream());
  in.close();
 }
 
 catch(Exception e)
 {
  System.out.println("Exception caught..."+e);
 }
 } // end savefile
  } // end class SaveFileApplet
   
  SECOND FILE: SaveFile Applet.html
   
  <html>
<head>
 <title>save file</title>
</head>
<body BGCOLOR=WHITE>
<div align="center">
<table WIDTH="70%" align="center">
<tr align="center" bgcolor="#CCC66H"><td><< SAVE FILE >></td></tr>
<tr align="center">
<td>
 <applet CODE="SaveFileApplet.class" WIDTH=500 HEIGHT=400>
 </applet>
</td>
</tr>
</table>
</div>
</body>
</html>

  THIRD FILE: SaveFileServlet.java 
   
  // C:\jakarta-tomcat-4.1.31\webapps\examples\WEB-INF\classes\SaveFileServlet.java
   
  import java.io.*;
import java.text.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
   
  public class SaveFileServlet extends HttpServlet {
 
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException
 {   
     String name = req.getParameter("filename");
     String content = req.getParameter("teditor");
     
     String nameFile = "C:/temp/"+name;
     
     FileWriter resultsFile = new FileWriter(nameFile,true);
     PrintWriter toFile = new PrintWriter(resultsFile,true);
     
     toFile.println(content);
     toFile.close();
 }   
}         

  Yours Sincerely,
  TEH NORANIS
  
Teh Noranis Mohd Aris <te...@yahoo.com> wrote:
  Dear All,

Thank you so much for the explanation, Mr. Christopher Schultz. I understand that by just using a "file" input type, I can upload a file directly. In fact, I already construct the program and it is already working. However, I choose to use applet to get the advantage of Java GUI programming, which is event-driven. Actually, the save file module is only part of the system. I'm going to try what has been suggested and I will get to you soon. Thank you so much. 

Yours Sincerely,
TEH NORANIS 

Christopher Schultz wrote:
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> In
> my program, I want the servlet to load an applet where I can input
> the file name in a given text field and the file content in a given
> text area.

Just out of curiosity, why do you want an applet to do this when you can
just use a "file" input type and upload a file directly?

> When the user has input the information, I want to POST
> the file name and its content from the applet to the servlet.

You are not using a POST. You are using a GET. If you want to use a
POST, you will have to write your file content to the request body,
instead of putting it into a URL parameter.

You had something like this:

String url = "http://.../servlet?filename=[name]&content=[contents]";

URLConnection conn = new URL(url).openConnection();
conn.connect();
conn.close();

Instead, you should do something like this:

String url = "http://...servlet?filename=[name]";
URLConnection conn = new URL(url).openConnection();
conn.setDoOutput(true);
conn.setHeader("Content-Length", contents.length());
conn.connect();

OutputStream out = conn.getOutputStream();
out.write(contents);
out.flush();
out.close();

conn.close();

This will put the contents of your file into the request body, instead
of in the URL parameters.

> I do not know whether I pass the
> parameters from the applet to the servlet correctly.

To check that the parameters are correct, put something like this into
your servlet code:

System.out.println("param[filename] = "
+ request.getParameter("filename"));

Also, you might want to print out the fill path of the file you are
trying to create. This really ought to do it:

File target = new File("C:\\TEMP", filename);

FileOutputStream out = new FileOutputStream(target);
out.write(contents);
out.flush();
out.close();

> After I input
> the file name and the file content, 2 files were created by the
> system: 1. a file with the name null 2. a source code file with a
> file name from the user input with no content at all.

I'm not sure how that extra file is being created. Your code only had a
single "open" call. Is it possible that "null" was created from an old
copy of the code, and you just forgot to delete the file?

Finally, don't use a FileWriter unless you know that you are dealing
with text. Otherwise, binary files will be corrupted. I'm not sure if
that matters to you, but creating a servlet that handles any type of
file will be more useful than one that only handles text.

> Yes, I'm using
> the same servlet to save a file and serving a page to save files.
> What is actually the matter with that approach?

It just seems that the "save file" servlet should do nothing but save a
file. Why have this servlet return any content at all? If I were writing
this "system", I would have the following files:

applet.html (contains element to serve the applet)
SaveFileServlet (saves files, as discussed)

When you want to display the applet, just display applet.html.
Otherwise, your SaveFileServlet will write to a file called "null" every
time you try to display the page (that's probably where your "null" file
is coming from).

Only call the SaveFileServlet when you actually want to save data.

- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF6b3n9CaO5/Lv0PARApg9AKCHsXSGif7v69laYl4u1DHmGvRrHACbB7cz
z2uU32oMdoJKcvL1/9EXf6A=
=sF79
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org




---------------------------------
Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out.

 
---------------------------------
TV dinner still cooling?
Check out "Tonight's Picks" on Yahoo! TV.

Re: File Content Not Saved To Server

Posted by Teh Noranis Mohd Aris <te...@yahoo.com>.
Dear All,
   
  Thank you so much for the explanation, Mr. Christopher Schultz. I understand that by just using a "file" input type, I can upload a file directly. In fact, I already construct the program and it is already working. However, I choose to use applet to get the advantage of Java GUI programming, which is event-driven. Actually, the save file module is only part of the system. I'm going to try what has been suggested and I will get to you soon. Thank you so much. 
   
  Yours Sincerely,
  TEH NORANIS  

Christopher Schultz <ch...@christopherschultz.net> wrote:
  -----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> In
> my program, I want the servlet to load an applet where I can input
> the file name in a given text field and the file content in a given
> text area.

Just out of curiosity, why do you want an applet to do this when you can
just use a "file" input type and upload a file directly?

> When the user has input the information, I want to POST
> the file name and its content from the applet to the servlet.

You are not using a POST. You are using a GET. If you want to use a
POST, you will have to write your file content to the request body,
instead of putting it into a URL parameter.

You had something like this:

String url = "http://.../servlet?filename=[name]&content=[contents]";

URLConnection conn = new URL(url).openConnection();
conn.connect();
conn.close();

Instead, you should do something like this:

String url = "http://...servlet?filename=[name]";
URLConnection conn = new URL(url).openConnection();
conn.setDoOutput(true);
conn.setHeader("Content-Length", contents.length());
conn.connect();

OutputStream out = conn.getOutputStream();
out.write(contents);
out.flush();
out.close();

conn.close();

This will put the contents of your file into the request body, instead
of in the URL parameters.

> I do not know whether I pass the
> parameters from the applet to the servlet correctly.

To check that the parameters are correct, put something like this into
your servlet code:

System.out.println("param[filename] = "
+ request.getParameter("filename"));

Also, you might want to print out the fill path of the file you are
trying to create. This really ought to do it:

File target = new File("C:\\TEMP", filename);

FileOutputStream out = new FileOutputStream(target);
out.write(contents);
out.flush();
out.close();

> After I input
> the file name and the file content, 2 files were created by the
> system: 1. a file with the name null 2. a source code file with a
> file name from the user input with no content at all.

I'm not sure how that extra file is being created. Your code only had a
single "open" call. Is it possible that "null" was created from an old
copy of the code, and you just forgot to delete the file?

Finally, don't use a FileWriter unless you know that you are dealing
with text. Otherwise, binary files will be corrupted. I'm not sure if
that matters to you, but creating a servlet that handles any type of
file will be more useful than one that only handles text.

> Yes, I'm using
> the same servlet to save a file and serving a page to save files.
> What is actually the matter with that approach?

It just seems that the "save file" servlet should do nothing but save a
file. Why have this servlet return any content at all? If I were writing
this "system", I would have the following files:

applet.html (contains     element to serve the applet)
SaveFileServlet (saves files, as discussed)

When you want to display the applet, just display applet.html.
Otherwise, your SaveFileServlet will write to a file called "null" every
time you try to display the page (that's probably where your "null" file
is coming from).

Only call the SaveFileServlet when you actually want to save data.

- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF6b3n9CaO5/Lv0PARApg9AKCHsXSGif7v69laYl4u1DHmGvRrHACbB7cz
z2uU32oMdoJKcvL1/9EXf6A=
=sF79
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org



 
---------------------------------
Never miss an email again!
Yahoo! Toolbar alerts you the instant new Mail arrives. Check it out.

Re: File Content Not Saved To Server

Posted by Christopher Schultz <ch...@christopherschultz.net>.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> In
> my program, I want the servlet to load an applet where I can input
> the file name in a given text field and the file content in a given
> text area.

Just out of curiosity, why do you want an applet to do this when you can
just use a "file" input type and upload a file directly?

> When the user has input the information, I want to POST
> the file name and its content from the applet to the servlet.

You are not using a POST. You are using a GET. If you want to use a
POST, you will have to write your file content to the request body,
instead of putting it into a URL parameter.

You had something like this:

String url = "http://.../servlet?filename=[name]&content=[contents]";

URLConnection conn = new URL(url).openConnection();
conn.connect();
conn.close();

Instead, you should do something like this:

String url = "http://...servlet?filename=[name]";
URLConnection conn = new URL(url).openConnection();
conn.setDoOutput(true);
conn.setHeader("Content-Length", contents.length());
conn.connect();

OutputStream out = conn.getOutputStream();
out.write(contents);
out.flush();
out.close();

conn.close();

This will put the contents of your file into the request body, instead
of in the URL parameters.

> I do not know whether I pass the
> parameters from the applet to the servlet correctly.

To check that the parameters are correct, put something like this into
your servlet code:

System.out.println("param[filename] = "
     + request.getParameter("filename"));

Also, you might want to print out the fill path of the file you are
trying to create. This really ought to do it:

File target = new File("C:\\TEMP", filename);

FileOutputStream out = new FileOutputStream(target);
out.write(contents);
out.flush();
out.close();

> After I input
> the file name and the file content, 2 files were created by the
> system: 1. a file with the name null 2. a source code file with a
> file name from the user input with no content at all.

I'm not sure how that extra file is being created. Your code only had a
single "open" call. Is it possible that "null" was created from an old
copy of the code, and you just forgot to delete the file?

Finally, don't use a FileWriter unless you know that you are dealing
with text. Otherwise, binary files will be corrupted. I'm not sure if
that matters to you, but creating a servlet that handles any type of
file will be more useful than one that only handles text.

> Yes, I'm using
> the same servlet to save a file and serving a page to save files.
> What is actually the matter with that approach?

It just seems that the "save file" servlet should do nothing but save a
file. Why have this servlet return any content at all? If I were writing
this "system", I would have the following files:

applet.html     (contains <object> element to serve the applet)
SaveFileServlet (saves files, as discussed)

When you want to display the applet, just display applet.html.
Otherwise, your SaveFileServlet will write to a file called "null" every
time you try to display the page (that's probably where your "null" file
is coming from).

Only call the SaveFileServlet when you actually want to save data.

- -chris
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF6b3n9CaO5/Lv0PARApg9AKCHsXSGif7v69laYl4u1DHmGvRrHACbB7cz
z2uU32oMdoJKcvL1/9EXf6A=
=sF79
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org


Re: File Content Not Saved To Server

Posted by Teh Noranis Mohd Aris <te...@yahoo.com>.
Dear All,
   
  First, thank you so much for the reply, Mr. Christopher Schultz. In my program, I want the servlet to load an applet where I can input the file name in a given text field and the file content in a given text area. When the user has input the information, I want to POST the file name and its content from the applet to the servlet. The servlet will then GET the parameters (file name and file content) from the applet and save the file content in C:/temp/ based on the file name that has been input. I do not know whether I pass the parameters from the applet to the servlet correctly. After I input the file name and the file content, 2 files were created by the system:
  1. a file with the name null
  2. a source code file with a file name from the user input with no content at all.
   
  The system should only create one file with a file name and the file content based on the user input. The main problem is that 2 files were created. One question that was asked to me is "Why are you saving a file AND serving a page in the same servlet?" Yes, I'm using the same servlet to save a file and serving a page to save files. What is actually the matter with that approach? Another question was about "What you want is a POST with the content of your file in the request body -- NOT in the request parameters". Can you please elaborate the statement? How should I actually solve this problem? Please explain in detail. I'm really waiting for a prompt reply. Thank you so much.
   
  Yours Sincerely,
  TEH NORANIS    

Christopher Schultz <ch...@christopherschultz.net> wrote:
  -----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> I want to save a file name and its content to the computer server at 
> directory C:/temp/. I've passed the file name and file content
> parameter from the applet to the servlet. The problem now is that the
> file name is created in the computer server directory but a 'null' is
> included in the file content. Can anyone please help me solve the
> problem why this is happening?

> servletUrl = new URL(servletName + "?filename="+filename+"&teditor="+teditor);
> con = servletUrl.openConnection();
> con.setUseCaches(false);
> 
> BufferedReader buf = new BufferedReader(new InputStreamReader(con.getInputStream()));

This isn't what you want to do. What you want is a POST with the content
of your file in the request body -- NOT in the request parameters.

That isn't to say that your attempt won't work... it's just that there
are many limitations on passing information through a URL (such as any
maximum URL length limits set by your web server).

> HttpSession session = req.getSession();
> PrintWriter out = res.getWriter();
> 
> out.println("");
> out.println("");
> out.println("");
> out.println("    Save File To Server");
>
> ...

This is a very odd way to do things. Why are you saving a file AND
serving a page to save files in the same servlet?

> String name = req.getParameter("filename");
> String content = req.getParameter("teditor");
> 
> String nameFile = "C:/temp/"+name;
> FileWriter resultsFile = new FileWriter(nameFile,true);
> PrintWriter toFile = new PrintWriter(resultsFile,true);
> toFile.println(content);
> toFile.close(); 

So, do you get a file in C:\TEMP\whatever? If so, what is the content of
the file. You said "a null"... do you mean a 0 byte file? Or the word
"null"?

- -chris

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF6KD09CaO5/Lv0PARAph4AJ0RFetzCrvK7kylCLOjfz0s2lNtngCfVgSg
06XYsRJpi0Bn/mEjBsAnp4I=
=6KXD
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org



 
---------------------------------
Access over 1 million songs - Yahoo! Music Unlimited.

Re: File Content Not Saved To Server

Posted by Christopher Schultz <ch...@christopherschultz.net>.
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Teh,

Teh Noranis Mohd Aris wrote:
> I want to save a file name and its content to the computer server at 
> directory C:/temp/. I've passed the file name and file content
> parameter from the applet to the servlet. The problem now is that the
> file name is created in the computer server directory but a 'null' is
> included in the file content. Can anyone please help me solve the
> problem why this is happening?

>   servletUrl = new URL(servletName + "?filename="+filename+"&teditor="+teditor);
>   con = servletUrl.openConnection();
>   con.setUseCaches(false);
>  
>   BufferedReader buf = new BufferedReader(new InputStreamReader(con.getInputStream()));

This isn't what you want to do. What you want is a POST with the content
of your file in the request body -- NOT in the request parameters.

That isn't to say that your attempt won't work... it's just that there
are many limitations on passing information through a URL (such as any
maximum URL length limits set by your web server).

>   HttpSession session = req.getSession();
>   PrintWriter out = res.getWriter();
>   
>   out.println("<html>");
>   out.println("<head>");
>   out.println("<title>Login</title>");
>   out.println("<center><h2>Save File To Server</h2>");
>
>   ...

This is a very odd way to do things. Why are you saving a file AND
serving a page to save files in the same servlet?

>      String name = req.getParameter("filename");
>      String content = req.getParameter("teditor");
>          
>      String nameFile = "C:/temp/"+name;
>      FileWriter resultsFile = new FileWriter(nameFile,true);
>      PrintWriter toFile = new PrintWriter(resultsFile,true);
>      toFile.println(content);
>      toFile.close();                   

So, do you get a file in C:\TEMP\whatever? If so, what is the content of
the file. You said "a null"... do you mean a 0 byte file? Or the word
"null"?

- -chris

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (MingW32)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org

iD8DBQFF6KD09CaO5/Lv0PARAph4AJ0RFetzCrvK7kylCLOjfz0s2lNtngCfVgSg
06XYsRJpi0Bn/mEjBsAnp4I=
=6KXD
-----END PGP SIGNATURE-----

---------------------------------------------------------------------
To start a new topic, e-mail: users@tomcat.apache.org
To unsubscribe, e-mail: users-unsubscribe@tomcat.apache.org
For additional commands, e-mail: users-help@tomcat.apache.org