0

I am creating a Java Web Application which takes data from a HTML form and saves it to a text file using a Servlet. However when I run the application I cannot see the text file anywhere so I am unsure if it was created successfully or not. Does anyone have any ideas why the file is not appearing?

Here is my code for the HTML form:

<html>
<head>
    <title>Register Customer</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <form name = "regcustomer" method = "get" action = "CustomerServlet" >
        Customer Name
        <input type="text" name="customerName"> <br>
        Customer Address 
        <input type="text" name="customerAddress"> <br> 
        Telephone Number
        <input type="text" name="telNo"> <br>
        Email
        <input type="text" name="email"> <br>
        Cost per KG shipped
        <input type="text" name="costPKG"> <br>
        <input type="submit" value="Register"> <br> <br>

        <a href="index.html">Back</a>
        </form>
</body>

And here is my code for the servlet:

package Servlets;

import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CustomerServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse 
response)
throws ServletException, IOException {
PrintWriter pw = response.getWriter();
String customerName;
customerName = request.getParameter("customerName");
String customerAddress = request.getParameter("customerAddress");
String telNo;
telNo = request.getParameter("telNo");
String email = request.getParameter("email");
String costPKG = request.getParameter("costPKG");

try{
File file = new File("C:/xyz.txt");
FileWriter fstream = new FileWriter(file,true);
try (BufferedWriter out = new BufferedWriter(fstream)) {
    out.write(customerName+" "+customerAddress+" "+telNo+" "+email+" 
"+costPKG);
    out.newLine();
}
pw.println("File is created successfully");
}

catch (IOException e){
System.err.println("Error: " + e.getMessage());
}
}
}

Any suggestions would be much appreciated

Ryan Dodd
  • 23
  • 1
  • 7

1 Answers1

0

Try adding the line:

@WebServlet(urlPatterns = { "/CustomerServlet" })

before:

public class CustomerServlet extends HttpServlet {

Note: If you are using old container (not implemented Servlet 3.0, like Tomcat 6.0), then you have to edit web.xml.

Kohei TAMURA
  • 4,970
  • 7
  • 25
  • 49