Communication between applet and servlet Java Code
Today i will discuss about the communication between applet and servlet’s, the most common problem faced by beginner’s during Java development . So taking the applet as front end , our servlet at middle and database at back end most probably MYSQL.
Beginning at the applet end put the given below code in applet class outside paint function (must) . Change the URL urlServlet = new URL(getCodeBase(), “points”) ,if your servlet location is different than default location. You can send any object through this connection .just create the object and send it through oos.writeObject(your object) .
Communication between applet and servlet Java Code –Applet Code
import java.applet.Applet; import java.awt.*; import java.awt.event.*; import java.io.*; import java.net.*; public class tank extends Applet { private URLConnection ServletConnection() throws MalformedURLException, IOException { URL urlServlet = new URL(getCodeBase(), "points"); URLConnection con = urlServlet.openConnection(); con.setDoInput(true); con.setDoOutput(true); con.setUseCaches(false); con.setRequestProperty("Content-Type", "application/x-java-serialized-object"); return con; } private void SendData() { try { String input="hi hello !!"; // sending string from applet to servlet URLConnection con = ServletConnection(); OutputStream outstream = con.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstream); oos.writeObject(input); oos.flush(); oos.close(); // receive string from servlet InputStream instr = con.getInputStream(); ObjectInputStream inputFromServlet = new ObjectInputStream(instr); String data = (String) inputFromServlet.readObject(); inputFromServlet.close(); instr.close(); outputField.setText(result); } catch (Exception ex) { ex.printStackTrace(); } } }
Communication between applet and servlet Java Code-Servlet Code
Now moving to our servlet whose name is points in root folder of our workspace(Server folder apache). The code given below simply accept the string send by the applet and send it back to applet.
import java.io.*; import javax.servlet.ServletException; import javax.servlet.http.*; public class points extends HttpServlet { public void doPost ( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { try { response.setContentType("application/x-java-serialized-object"); InputStream in = request.getInputStream(); ObjectInputStream inputFromApplet = new ObjectInputStream(in); String abc = (String) inputFromApplet.readObject(); // receiving string from applet OutputStream outstr = response.getOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(outstr); oos.writeObject(abc); // sending string back to applet oos.flush(); oos.close(); } catch (Exception e) { e.printStackTrace(); } } }
Leave a Reply