Solved

How to Write and Read file in JSP ?

Posted on 2004-04-23
14
1,915 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
  • 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
 
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
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 

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

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Performance in games development is paramount: every microsecond counts to be able to do everything in less than 33ms (aiming at 16ms). C# foreach statement is one of the worst performance killers, and here I explain why.
Find out what the Office 365 disclaimer function is, why you would use it and its limited ability to create Office 365 signatures.
Here's a very brief overview of the methods PRTG Network Monitor (https://www.paessler.com/prtg) offers for monitoring bandwidth, to help you decide which methods you´d like to investigate in more detail.  The methods are covered in more detail in o…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

760 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now