java - Applet - server communication, how can I can do it? -
i have applet , must send request web application data server in database. working objects , useful server responses me objects!!
how applet can communicate server?
i think web services method, rmi and... make me happy, best , reliable?
as long applet communicating server can use serialized object. need maintain same version of object class in both applet jar , on server. not open or expandable way go quick far development time , pretty solid.
here example.
instantiate connection servlet
url servleturl = new url("<url servlet>"); urlconnection servletconnect = servleturl.openconnection(); servletconnect.setdooutput(true); // allow write url servletconnect.setusecaches(false); // write message servlet , not browser's cache servletconnect.setrequestproperty("content-type","application/x-java-serialized-object");
get output stream , write object
mycustomobject myobject = new mycustomobject() objectoutputstream outputtoservlet; outputtoservlet = new objectoutputstream(servletconnection.getoutputstream()); outputtoservlet.writeobject(myobject); outputtoservlet.flush(); //cleanup outputtoservlet.close();
now read in response
objectinputstream in = new objectinputstream(servletconnection.getinputstream()); myrespobject myrespobj; try { myrespobj= (myrespobject) in.readobject(); } catch (classnotfoundexception e1) { e1.printstacktrace(); } in.close();
in 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 object passed myrespobject myrespobj= new myrespobject(); return myrespobj; }
just remember both objects passing need implement serializable
public class mycustomobject implements java.io.serializable {
Comments
Post a Comment