正如标题所说,使用servlet时不会创建文件。我有一个简单的Web应用程序,我想从HTML中获取输入并将其写入.txt文件。问题是,一切运行良好,我没有得到任何错误或异常,它只是没有创建文本文件。我使用了相同的代码(用于创建文本文件),并将其测试到一个单独的类中,它完美地运行。问题是当我尝试在servlet中创建一个文本文件时。这是我的代码:
@WebServlet("/home")
public class HomePage extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.sendRedirect("/home.html");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
String add = request.getParameter("buttonAdd");
String read = request.getParameter("buttonRead");
String update = request.getParameter("buttonUpdate");
String delete = request.getParameter("buttonDelete");
if(add != null)
{
String title = request.getParameter("dvd_title");
String year = request.getParameter("dvd_year");
String price = request.getParameter("dvd_price");
if(!title.equals("") && !year.equals("") && !price.equals(""))
{
if(!Character.isDigit(title.charAt(0)))
{
if (isNumeric(year) && isNumeric(price))
{
try
{
List<String> lines = Arrays.asList("Title: " + title, "Year: " + year, "Price: " + price);
Path file = Paths.get("DVD - " + title + ".txt");
Files.write(file, lines, Charset.forName("UTF-8"));
}
catch(IOException e)
{
e.printStackTrace();
}
}
else
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Year and price must be numbers");
}
}
else
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Title cannot start with a number");
}
}
}
if(read != null)
{
System.out.println("2");
}
if(update != null)
{
System.out.println("3");
}
if(delete != null)
{
System.out.println("4");
}
}
private static boolean isNumeric(String s)
{
return s != null && s.matches("[-+]?\\d*\\.?\\d+");
}
}
答案 0 :(得分:0)
显然,它在Apache Tomcat / bin文件夹中创建文件,而不是在项目文件夹中。我的错。感谢JB Nizet的帮助。