Vous êtes sur la page 1sur 2

1)Here is the code of 'ServletExample.java' import java.io.*; import javax.servlet.*; import javax.servlet.http.

*; public class ServletExample extends HttpServlet{ public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException , IOException{ ObjectOutputStream output = null; try{ output = new ObjectOutputStream(response.getOutputStream()); String str = new String("Hello World"); output.writeObject(str); output.flush(); output.close(); System.out.println("Message is===== " + str); } catch( Exception e){ e. printStackTrace(); } } } 2)Now call the servlet with the 'AppletCallingServlet.java' import java.io.*; import java.awt.*; import java.net.*; import java.applet.*; public class AppletCallingServlet extends Applet{ URL url = null; URLConnection servletConnection = null; public void init() { try{ url = new URL("http://localhost:8080/examples/ServletExample" ;;); servletConnection = url.openConnection(); servletConnection.setDoInput(true); servletConnection.setDoOutput(true); servletConnection.setUseCaches(false); servletConnection.setDefaultUseCaches(false); servletConnection.setRequestProperty("Content-Type","application/octet-stream"); } catch(Exception e){ e.printStackTrace(); } } public void paint(Graphics g) { try{ ObjectInputStream input = new ObjectInputStream(servletConnection.getInputStream()); g.drawString("Applet Servlet Communication",50,50); String str = new String(); str = (String)input.readObject(); g.drawString(" Message sent from server: " + str,50,100); input.close(); } catch( Exception e) {

e.printStackTrace(); } } } 3)Call this applet with the html file. <html> <body> <h1>Java Applet Demo</h1> <applet code=AppletCallingServlet.class width=500 height=500> </applet> </body> </html>

Vous aimerez peut-être aussi