Java – applet – server communication, what should I do?
I have an applet and I have to send a request to the web application to get data from the server in the database I am using the object, the server response object is very useful!!
How does the applet communicate with the server?
I think web services methods, RMI and... Make me happy, but which is the best and reliable?
Solution
As long as your applet communicates with the server, you can use serialized objects You only need to maintain the same version of the object class on the applet jar and the server It is not the most open or extensible way, but it is fast in development time and quite stable
This 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 the object
MyCustomObject myObject = new MyCustomObject() ObjectOutputStream outputToServlet; outputToServlet = new ObjectOutputStream(servletConnection.getOutputStream()); outputToServlet.writeObject(myObject); outputToServlet.flush(); //Cleanup outputToServlet.close();
Now read the reply
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; }
Remember that both objects you pass need to be serializable
public Class MyCustomObject implements java.io.Serializable {