Solved

How to Write and Read file in JSP ?

Posted on 2004-04-23
14
1,930 Views
Last Modified: 2010-04-01
Hi Experts;

I'm new in JSP but not in Java. I have a webserver for my JSP, now I created
a simple forum which temporarily displays the message in the other TextArea what
I wanna do is to be able to write those messages into a file and read them back
like a normal forum.

How can I do this in jsp here are my html codes :

<html>
<head>
<title>::: GuestBook :::</title>
</head><body>

<!--JavaScript to filter certain words !-->
<script language="javascript" src="Codes.js"></script>

<center><form name="frmx">
<br><br><br>
<font face="arial" size="3" color="black">
<b>Thank you for visiting !</b></font>
<br><font face="arial" size="2"><br>
Pls. Take a moment to sign this guessbook<br>
Always hoping for your next visit thanks.<br><br>
Name : <input type=field name="fld1" cols="30"><br><br>
<textarea name="txt1" cols="30" rows="8">
</textarea><br>Previous Comments :<br>
<textarea readonly name="txt2" cols="30" rows="8"></textarea><br><br>
<input type="button" name="cmdbtn1" onclick="testMe()" value="Sign the Guestbook">
<input type="button" name="cmdbtn2" onclick="clearMe()" value="Clear Me">
</form></center>
</body>
</html>

Hoping for your responce :
simple21
0
Comment
Question by:simple21
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
  • 3
  • +2
14 Comments
 
LVL 27

Expert Comment

by:rrz
ID: 10905786
You can use the following,  if you are using JSSE 1.4      
FileWriter fw = new FileWriter(filename,true);
0
 

Author Comment

by:simple21
ID: 10906109
I tried this but it does not work :

<html>
<head>
<title>::: GuestBook :::</title>
</head><body>

<script language="javascript" src="Codes.js"></script>
<center><form name="frmx">
<br><br><br>
<font face="arial" size="3" color="black">
<b>Thank you for visiting !</b></font>
<br><font face="arial" size="2"><br>
Pls. Take a moment to sign this guessbook<br>
Always hoping for your next visit thanks.<br><br>
Name : <input type=field name="fld1" cols="30"><br><br>
<textarea name="txt1" cols="30" rows="8">
</textarea><br>Previous Comments :<br>
<textarea readonly name="txt2" cols="30" rows="8"></textarea><br><br>
<input type="button" name="cmdbtn1" onclick="testMe()" value="Sign the Guestbook">
<input type="button" name="cmdbtn2" onclick="clearMe()" value="Clear Me">
</form></center>

<%@ page import="java.io.*"%>
<%
  String text = request.getParameter("txt1");
  try {
    FileWriter fw = new FileWriter(System.getProperty("user.dir") + "\\Sample.txt", true);
    fw.write(text);
    fw.flush();
    fw.close();
  }
  catch (IOException ioe) {
    out.println(ioe.toString());
  }
%>

</body>
</html>

How to a write the file after pressing the cmdbtn1 button?
What em I doing wrong ?
0
 
LVL 92

Expert Comment

by:objects
ID: 10906493
i'd implement the writing of the file in a servlewt and have your jsp form call that servlet.
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 14

Assisted Solution

by:sudhakar_koundinya
sudhakar_koundinya earned 20 total points
ID: 10906757
i THINK YOU ARE EXPECTING SOME THING LIKE THIS.




<%@ page import="java.io.*"%>
<html>
<head>
<title>::: GuestBook :::</title>
</head><body>

<%!
   public String GetText(String file)
   {
         try
         {
            FileInputStream fin=new FileInputStream(file);
            if(fin.available()>0)
         {
            byte array[]=new byte[fin.available()];
            fin.read(array);
            fin.close();
            return new String(array);
         }
         else
         {
               return "";
         }
         }
         catch(Exception ex)
         {
               return "";
         }

   }
%>
<%
String textPath=getServletContext().getRealPath("/Sample.txt");
%>


<%
  String text = request.getParameter("txt1");
 String text2 = request.getParameter("fld1");
 if(text2==null) text2="Unknown";
 if(text==null)
text=  "";
text=text.trim();

{
  try {
        String text1=GetText(textPath).trim();

      FileOutputStream fout=new FileOutputStream(textPath);
      text=(text1+"\r\n"+text2 +" Says :"+text+"\r\n");
    fout.write(text.getBytes());
    fout.close();
  }
  catch (IOException ioe) {
    out.println(ioe.toString());
  }
  }
%>

<script language="javascript" src="Codes.js"></script>
<center><form name="frmx" action="a.jsp" method="post">
<br><br><br>
<font face="arial" size="3" color="black">
<b>Thank you for visiting !</b></font>
<br><font face="arial" size="2"><br>

Pls. Take a moment to sign this guessbook<br>
Always hoping for your next visit thanks.<br><br>
Name : <input type=field name="fld1" cols="30"><br><br>
<textarea name="txt1" cols="30" rows="8" >
</textarea><br>Previous Comments :<br>
<textarea readonly name="txt2" cols="30" rows="8" value=''><%=text%></textarea><br><br>

<input type="submit" name ="submit" value "submit">
</form></center>




</body>
</html>
0
 
LVL 23

Assisted Solution

by:rama_krishna580
rama_krishna580 earned 20 total points
ID: 10906994
0
 
LVL 27

Accepted Solution

by:
rrz earned 440 total points
ID: 10907860
Here is some quick and dirty JSP. I just want to demonstrate my idea. Please ask us any follow up questions you have about this.   Depending on your system,you might(I did not) have to manually create  the "Sample.txt" file.  "Sample.txt" will be located in your context's root directory.      rrz

<%@ page import="java.io.*"%>
<%
  String text = request.getParameter("txt1");
  String name = request.getParameter("fld1");
  if(name==null||name.trim().equals(""))name="anonymous";
  if(text!=null&&!text.trim().equals("")){
      try{
          FileWriter fw = new FileWriter(new File(application.getRealPath("Sample.txt")), true);
                fw.write(name + ": " + text + "\r\n");
                fw.flush();
                fw.close();
         } catch (IOException ioe) {}
  }
%>
<html>
<head>
<title>::: GuestBook :::</title>
</head><body>
<center><form name="frmx">
<font face="arial" size="3" color="black">
<b>Thank you for visiting !</b></font>
<br><font face="arial" size="2"><br>
Pls. Take a moment to sign this guestbook<br/>
Always hoping for your next visit thanks.<br/>
Name : <input type=field name="fld1" cols="30"/><br/>
<textarea name="txt1" cols="30" rows="8"/></textarea><br/>
Previous Comments :<br/>
<textarea readonly name="txt2" cols="30" rows="8">
<jsp:include page="Sample.txt"/></textarea><br/><br/>
<input type="submit" name="cmdbtn1" value="Sign the Guestbook"/>
</form></center>
</body>
</html>
0
 

Author Comment

by:simple21
ID: 10909852
rrz@871311;

Thanks but where do I put my Sample.txt ? I manually created it and put it on the same folder as my jsp file
it accepts the message but it doesnt display the message and it doesnt write the message in Sample.txt
I'm using Blazix as my Java Server, thanks.
0
 

Author Comment

by:simple21
ID: 10909869
sudhakar_koundinya;

It did not work it gave me an error :

Error(s) in compiling C:\Software\Blazix\webfiles\test\job4\Sample.jsp
C:\Software\Blazix\jspdir\test\job4\Sample_jsp.java:71: cannot resolve symbol
symbol  : method getServletContext ()
location: class desisoft_jsp_Sample_jsp1082849647292
String textPath=getServletContext().getRealPath("/Sample.txt");
                ^
1 error
0
 
LVL 27

Assisted Solution

by:rrz
rrz earned 440 total points
ID: 10910053
>where do I put my Sample.txt ?  
I put it in my context's root folder. I am using Tomcat.
I used the following line to get it's path.
application.getRealPath("Sample.txt")  
This is where I put it.
Tomcat\webapps\myContext\Sample.txt  

I don't know anything about  Blazix    rrz
0
 
LVL 27

Expert Comment

by:rrz
ID: 10910097
>C:\Software\Blazix\webfiles\test\job4\Sample.jsp
Is "test"  your context ?  
If so, then put  Sample.txt in the test folder.    

>cannot resolve symbol
>symbol  : method getServletContext ()  
this is a servlet method that returns the "application" implicit JSP object.  
rrz
0
 

Author Comment

by:simple21
ID: 10910255
>C:\Software\Blazix\webfiles\test\job4\Sample.jsp
>Is "test"  your context ?  

Its writing now but it does not display the word on the textarea
after submitting it. Its should display it right :

// This one should call it right but it doesnt ?
<textarea readonly name="txt2" cols="30" rows="8">
<jsp:include page="Sample.txt"/>

So, whats the problem ?

0
 
LVL 92

Assisted Solution

by:objects
objects earned 20 total points
ID: 10910278
is Sample.txt in the same directory as your jsp?
0
 

Author Comment

by:simple21
ID: 10910313
Haha I figured it out . . .
0
 
LVL 92

Expert Comment

by:objects
ID: 10910355
:)
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
Exception creating bean of class 5 219
love6 challenge java 31 133
struts exact match support 3 59
batch vs regular insert in spring DAO 2 23
In Part II of this series, I will discuss how to identify all open instances of Excel and enumerate the workbooks, spreadsheets, and named ranges within each of those instances.
This article was originally published on Monitis Blog, you can check it  here .   Some years back, I worked as the CTO.  During my tenure, I had a head of IT support reporting to me.  He did his job quite well and had a commendable sense of duty…
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

749 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question