writeAppend.jsp <html> <head> <title>Append a file</title> </head> <body bgcolor="#000000"> <jsp:useBean id="writer" class="WriteAppend" scope="request"> <jsp:setProperty name="writer" property="path" value="/path/to/afile.txt" /> <jsp:setProperty name="writer" property="something" value="Something already set as a property in WriteAppend" /> </jsp:useBean> <h3>Write to the file</h3> <p> <% writer.setSomething("Something to write to the file"); out.print(writer.getSomething()); out.print(writer.writeSomething()); %> </p> </body> </html> WriteAppend.Java import Java.io.*; public class WriteAppend { private String path; private String something; // WriteAppend构造器,用于初始化参数 public WriteAppend() { path = null; something = "Default message"; } //设置path参数 public void setPath(String apath) { path = apath; } //获取path参数值 public String getPath() { return path; } //设置参数something public void setSomething(String asomething) { something = asomething; } //获取something参数 public String getSomething() { return something; } //追加操作 public String writeSomething() { try { FileWriter theFile = new FileWriter(path,true); PrintWriter out = new PrintWriter(theFile); out.print(something + "\n"); out.close(); theFile.close(); return "Das war sehr gut!"; } catch (IOException e) { return e.toString(); } } } |