如何使用Servlet在Java中写入文件

时间:2017-08-04 02:07:23

标签: java html servlets netbeans

我正在创建一个Java Web应用程序,它从HTML表单中获取数据并使用Servlet将其保存到文本文件中。但是当我运行应用程序时,我无法在任何地方看到文本文件,因此我不确定它是否已成功创建。有没有人知道文件没有出现的原因?

以下是我的HTML表单代码:

<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>

这是我的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());
}
}
}

非常感谢任何建议

1 个答案:

答案 0 :(得分:0)

尝试添加以下行:

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

之前:

public class CustomerServlet extends HttpServlet {

注意:如果您使用的是旧容器(未实现Servlet 3.0,如Tomcat 6.0),那么您必须编辑web.xml。