Applet-server communication, how can I do this?

I have an applet, and I have to send a request to a web application to receive data from a server that is in the database. I work with objects, and it is very useful that the server answers me with objects!

How can an applet interact with a server?

I think that the web services method, RMI and ... make me happy, but which one is the best and reliable?

+3
source share
1 answer

So far, only your applet interacting with the server can use a serialized object. You just need to maintain the same version of the feature class in both applets and the server. This is not the most open or extensible way, but it is fast, as long as the development time is pretty solid.

Here is an example.

Create a Servlet Connection

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 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 answer

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 of the objects you pass must implement serializable

 public Class MyCustomObject implements java.io.Serializable
 {
+4
source

Source: https://habr.com/ru/post/1717070/


All Articles