How can my applet or application communicate with my servlet?
Created May 4, 2012
Alex Chaffee
It's pretty straightforward. You can use the java.net.URLConnection and java.net.URL classes to open a standard HTTP connection to the web server. The server then passes this information to the servlet in the normal way.
Basically, the applet pretends to be a web browser, and the servlet doesn't know the difference. As far as the servlet is concerned, the applet is just another HTTP client.
(Of course, you can write a servlet that is meant to be called only by your applet, in which case it *does* know the difference. You can also open a ServerSocket on a custom TCP port, and have your applet open a Socket connection. You must then design and implement a custom socket-level protocol to handle the communication. This is how you could write, e.g., a Chat applet communicating with a servlet. In general, a custom protocol requires more work than HTTP, but is more flexible. However, custom protocols have a harder time getting through firewalls.)
For more detail, you can see the Sun Web Server FAQ (http://www.sun.com/software/jwebserver/faq/faq.html) Questions C8 (http://www.sun.com/software/jwebserver/faq/faq.html#c8) and C9 (http://www.sun.com/software/jwebserver/faq/faq.html#c9) .
Also, Chad Darby has an article with source code (http://www.j-nine.com/pubs/applet2servlet/index.htm) on the subject.
And Netscape DevEdge Online has a similar article - Applet-to-Servlet Communication for Enterprise Applications (http://developer.netscape.com/viewsource/index_frame.html?content=fields_servlet/fields_servlet.html) skip to the "Communication Tactics" section to get to the good part.
See also:
- How can I pass an object from an applet to a servlet ?
- When you communicate with a servlet from an Applet, how can you ensure that the session information is preserved? That is, how do you manage cookies in applet-servlet communication?
- How can an applet or application pass data to and read output from a CGI script or Servlet?
- see the section "An Applet That Sends POST Data" here - http://archive.coreservlets.com/Chapter17.html