Hi,
I have a jsp page that contains a form.When i click the submit button of the form i am directed to a servlet.I would like to create a text file using this servlet and write to it the form data collected from the earlier jsp page.
Jsp Page-Page1.jsp
Kindly help me as to how do i code for the Page1Servlet so that am able to collect the passed data from jsp page,Page1.jsp,ad write it to a text file.
Regards.
Jimmy Clark
Ranch Hand
Joined: Apr 16, 2008
Posts: 2187
posted
0
First you should create a class that will write data to a text file using some same data. Forget about the Servlet and the JSP page for a while, just concentrate on creating a class that can write data to a text file.
Once you have this class ready, then start to think about how you would instantiate an object of this class in the servlet code and pass the data that was entered in the HTML form of the JSP page.
The key aspect here is that the logic for writing to a text file should not be written directly in a Servlet sub-class.
The request.getParameter() method will let you grab the submitted request parameters. Once you have the data, writing a file is simple matter of normal Java file I/O.
You can create a helper class that will write the name and age parameters to given file.
For example
- Create a helper class that will have a method like writeToFile which takes three parameters (path, name, age)
- The method would open a file using given path, and append the name and age
- The servlet will use the helper to write the name and age information to the file.
- Do not write the IO code directly in servlet
- You may want to consider thread safety issues
And, why do you need to write it to a file ? If you want to just store it and retrieve later , a database is better at storing and querying then a simple text file.
Thanks a lot for the suggestions.Its working for me now.However i have a doubt.The text file that am creating is getting stored in my eclipse workspace:-
Is creating a file to this location is same as creating a file on the Server?I am using Tomcat Server and Eclipse Helios.
Kindly reply.
Regards.
Jimmy Clark
Ranch Hand
Joined: Apr 16, 2008
Posts: 2187
posted
0
Sounds good. You should be able to create a file anywhere you want, and more experience with the I/O API should help.
Is creating a file to this location is same as creating a file on the Server?
You would have to clarify what "on the Server" means to you? Based on the directory you provide, it seems like the file is being created in an IDE directory. If you want it created somewhere else, you would have to change this with code.