-1

I was wondering how I can store a parameter that has been passed to my servlet Java file from a JSP file.

This is what I have so far

JSP FILE

<form action = "LogControl" method = "POST">
     <input type="radio" name="seat_selected" value="A1" checked> Seat A1<br>
     <input type="radio" name="seat_selected" value="A2"> Seat A2<br>
     <input type="radio" name="seat_selected" value="A3"> Seat A3<br>
     <br />
     <input type = "submit" value = "Submit" />

LogControl.java

   // Method to handle POST method request.
public void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    doGet(request, response);



            PrintWriter writer = new PrintWriter("test.txt", "UTF-8");
            writer.println(request.getParameter("seat_selected"));
            writer.close();

    out.println("<a href=\"index.html\">HOME</a>");
}

For some reason, it is not creating the file or if I created the file for it, it is not storing anything there.

Cheers

user1427806
  • 73
  • 1
  • 2
  • 10
  • Possible duplicate of [How to use PrintWriter and File classes in Java?](https://stackoverflow.com/questions/11496700/how-to-use-printwriter-and-file-classes-in-java) – Cypher Mar 20 '18 at 01:48

1 Answers1

1

There are 2 ways here:

1- If you want to store the value in a variable, just do

String seat_selected = request.getParameter("seat_selected");

and then just use this variable to perform operations.

2- If you want to store the value in a file, then you can do something like:

File fileobj = new File("C:/Users/Me/Desktop/directory/file.txt");
fileobj.getParentFile().mkdirs();
PrintWriter printWriter = new PrintWriter(fileobj);
printWriter.println(request.getParameter("seat_selected"));
printWriter.close();
hiren
  • 1,067
  • 1
  • 9
  • 16
  • This does work. But if I submit the previous form it overrides the first file. How do I get it to go to a new line? – user1427806 Mar 20 '18 at 08:33
  • It will override since you are supplying the same file to the `File`. So you want to store the value in different file everytime? – hiren Mar 20 '18 at 08:52
  • I would like it to store in the same file but on a new line. ATM whenever a user uses the form it places the value into the first line overriding whatever was there. I would like each time a user uses the form there result goes onto an empty line, cheers. – user1427806 Mar 20 '18 at 09:00
  • To do this, you need to open the file in `append` mode. Try this: `PrintWriter pw = new PrintWriter(new FileOutputStream( new File(fileobj), true /* append = true */)); ` – hiren Mar 20 '18 at 09:05
  • I used BufferedWriter pw = new BufferedWriter(new FileWriter("FILELOCATION", true)); and that seemed to work, thanks for the help – user1427806 Mar 20 '18 at 09:16