java – Applet – 服务器通信,我该怎么办呢?
发布时间:2020-12-15 02:12:41 所属栏目:Java 来源:网络整理
导读:我有一个applet,我必须向Web应用程序发送请求,以从数据库中的服务器获取数据.我正在使用对象,服务器响应对象非常有用!! applet如何与服务器通信? 我认为Web服务方法,RMI和…让我开心,但哪个最好又可靠? 解决方法 只要您的applet与服务器通信,您就可以使用
我有一个applet,我必须向Web应用程序发送请求,以从数据库中的服务器获取数据.我正在使用对象,服务器响应对象非常有用!!
applet如何与服务器通信? 我认为Web服务方法,RMI和…让我开心,但哪个最好又可靠? 解决方法
只要您的applet与服务器通信,您就可以使用序列化对象.您只需要在applet jar和服务器上维护相同版本的对象类.它不是最开放或可扩展的方式,但它在开发时间和相当稳固方面很快.
这是一个例子. 实例化与servlet的连接 URL servletURL = new URL("<URL To your Servlet>"); URLConnection servletConnect = servletURL.openConnection(); servletConnect.setDoOutput(true); // to allow us to write to the URL servletConnect.setUseCaches(false); // Write the message to the servlet and not from the browser's cache servletConnect.setRequestProperty("Content-Type","application/x-java-serialized-object"); 获取输出流并编写对象 MyCustomObject myObject = new MyCustomObject() ObjectOutputStream outputToServlet; outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream()); outputToServlet.writeObject(myObject); outputToServlet.flush(); //Cleanup outputToServlet.close(); 现在阅读回复 ObjectInputStream in = new ObjectInputStream(servletConnection.getInputStream()); MyRespObject myrespObj; try { myrespObj= (MyRespObject) in.readObject(); } catch (ClassNotFoundException e1) { e1.printStackTrace(); } in.close(); 在你的servlet中 public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { MyRespObject myrespObj= processSomething(request); response.reset(); response.setHeader("Content-Type","application/x-java-serialized-object"); ObjectOutputStream outputToApplet; outputToApplet = new ObjectOutputStream(response.getOutputStream()); outputToApplet.writeObject(myrespObj); outputToApplet.flush(); outputToApplet.close(); } private MyRespObject processSomething(HttpServletRequest request) { ObjectInputStream inputFromApplet = new ObjectInputStream(request.getInputStream()); MyCustomObject myObject = (MyCustomObject) inputFromApplet.readObject(); //Do Something with the object you just passed MyRespObject myrespObj= new MyRespObject(); return myrespObj; } 请记住,您传递的两个对象都需要实现可序列化 public Class MyCustomObject implements java.io.Serializable { (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |