Applet - server communication, how can I can do it?

穿精又带淫゛_ 提交于 2019-11-27 23:21:26

As long as its only your applet communicating with the server you can use a serialized object. You just need to maintain the same version of the object class in both the applet jar and on the server. Its not the most open or expandable way to go but it is quick as far as development time and pretty solid.

Here is an example.

Instantiate the connection to the 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");

Get the output stream and write your object

MyCustomObject myObject = new MyCustomObject()
ObjectOutputStream outputToServlet;
outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream());
outputToServlet.writeObject(myObject);
outputToServlet.flush(); //Cleanup
outputToServlet.close();

Now read in the response

ObjectInputStream in = new ObjectInputStream(servletConnection.getInputStream());
MyRespObject myrespObj;
try
{
    myrespObj= (MyRespObject) in.readObject();
} catch (ClassNotFoundException e1)
{
    e1.printStackTrace();
}

in.close();

In your 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;
}

Just remember that both Objects that you are passing need to implement serializable

 public Class MyCustomObject implements java.io.Serializable
 {
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!