我正在处理JSP
和servlet
。
下面的代码有效,但我希望它更具动态性。
这是我的JSP
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<form ACTION="Servlet" method="POST">
<body><h1>Data Mahasiswa</h1>
<table>
<tr><td>Nama </td>
<td>: <input type="text" name="Name" value="" /></td>
</tr>
<tr><td>NIM </td>
<td>: <input type="text" name="ID" value="" /></td>
</tr>
<tr><td>Progdi </td>
<td>: <input type="radio" name="Member" value="Not Member" />Not Member
<input type="radio" name="Member" value="Member" />Member
</td>
</tr>
</table>
<input type="submit" value="SAVE" />
</form>
</body>
</html>
&#13;
这是我的Servlet
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Servlet extends HttpServlet {
private String temp;
private BufferedWriter writer;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String s1 = request.getParameter("Name");
String s2 = request.getParameter("ID");
String s3 = request.getParameter("Member");
try{
try {
String text = (s1 + " | " + s2 + " | " + s3);
File file = new File("D:/write.txt");
writer = new BufferedWriter(new FileWriter(file));
writer.write(text);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
finally{
out.println("<h1> Data Saved <h1>");
}
}
我想将输出write.txt设为如下
Bill | 788878 | Member
Mark | 655598 | Member
Ron | 953116 | Not Member
当前代码仅适用于1行。
我的意思是,每次重新输入输入数据,它们都会写在输出txt文件的下一行。
答案 0 :(得分:0)
请尝试
writer = new BufferedWriter(new FileWriter(file, true));
。
额外true
指定写入模式为append
,而不是over write
append - 布尔值如果为true,则数据将被写入 文件而不是开头。