如何从servlet编写输出连续行



我正在研究JSPservlet。下面的代码可以工作,但我希望它更动态。

这是我的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>

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

我想让我的输出如下所示

Bill | 788878 | Member
Mark | 655598 | Member
Ron | 953116 | Not Member

当前代码只适用于一行

我的意思是,每次重新输入数据,它们将被写入输出文本文件的下一行。

请尝试writer = new BufferedWriter(new FileWriter(file, true)); .

额外的true指定写模式为append,而不是over write

append -布尔值如果为true,则数据将被写入数组的末尾文件而不是开头。

相关内容

  • 没有找到相关文章

最新更新