众所都知见于安全性考虑,applet在ie、netscape中没有写入文件的能力,包括本地、服务器文件。那么我们怎样才能实现一些数据的保留呢?(象本程序代码中记录积分的功能)。
一个方法是通过服务器端的servlet写入文件,applet端的代码如下:
private void Send(){ message=score+"#"+tf.getText (); showStatus("Message send"); String queryString="/servlet/javaduke.servlet.SaveServlet?message="+ URLEncoder.encode(message); p("Attempting to send:"+message); try{ connect=(new URL(chatURL,queryString)).openConnection(); showStatus("打开连接"); showStatus(connect.toString ()); System.out.println("open connection"); connect.setDefaultUseCaches(false); connect.setUseCaches (false); connect.setDoInput (true); connect.setDoOutput(false); System.out.println("dooutput false"); connect.connect(); System.out.println("open stream"); p("Made connection to"+connect); showStatus("试图连接、读取回应"); InputStreamReader reader=new InputStreamReader(connect.getInputStream ()); BufferedReader in=new BufferedReader(reader); message=in.readLine (); while(message!=null){ tf.setText(message); message=in.readLine (); } showStatus("对话成功"); } catch(MalformedURLException e2){ System.err.println ("MalformedURLException!"); e2.printStackTrace (System.err ); showStatus("MalformedURLException"); } catch(IOException e1){ System.err.println ("IOException"); e1.printStackTrace (System.err); showStatus(e1.toString ()); } } server端代码如下! Servlet写入文件(www.mycgiserver.com调试成功)
import javax.servlet.http.*; import java.io.*; import java.util.*;
public class SaveServlet extends HttpServlet { String counter,counter2; //Initialize global variables public void init(ServletConfig config) throws ServletException { super.init(config); } //Service the request public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
File file=new File("/members/YourID/servlet/gamelog.txt"); RandomAccessFile raf; if(!file.exists()){ raf=new RandomAccessFile(file,"rw"); counter="210#javaduke "; raf.seek(0); raf.writeBytes(counter); raf.close(); } else{ counter=request.getParameter("message"); raf=new RandomAccessFile(file,"rw"); raf.seek(0); raf.writeBytes(counter); raf.close(); } response.setContentType("text/html"); PrintWriter out = new PrintWriter (response.getOutputStream()); out.print("Saved OK!"); out.close();
}
//Get Servlet information public String getServletInfo() { return "game.SaveServlet Information"; } } |