Solved

How to Write and Read file in JSP ?

Posted on 2004-04-23
14
1,924 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
Javascript onclick event 4 107
Display the newly inserted values 3 77
servlet concurrency 13 102
difference between projection and projection list in hibernate 1 110
This article outlines the process to identify and resolve account lockout in an Active Directory environment.
Each year, investment in cloud platforms grows more than 20% (https://www.immun.io/hubfs/Immunio_2016/Content/Marketing/Cloud-Security-Report-2016.pdf?submissionGuid=a8d80a00-6fee-4b85-81db-a4e28f681762) as an increasing number of companies begin to…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.
With Secure Portal Encryption, the recipient is sent a link to their email address directing them to the email laundry delivery page. From there, the recipient will be required to enter a user name and password to enter the page. Once the recipient …

803 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