How do I pass session information from a JSP to a Applet. Can I pass them as parameters or can I talk back from an Applet to the JSP page?
Created May 4, 2012
<applet code="foo.class" width="100" height="100"> <% for (x = 0; x < session.fooData.getCount(); x++) { %> <param name="<%= session.fooData.getName(x) %>" value="<%= session.fooData.getValue(x) %>"> <% } %> </applet>
If you want to have the applet be able to talk back to the server as it runs you can do that too. In this case the applet should not communicate with the JSP that hosted it but rather with a servlet running in the same web application. Both the JSP and the servlet would share the same session info so you have access to the same data. The following example uses serialized object to pass the information back and forth but you could form the requests and responses with plain text or xml or whatever. The applet needs to open a connection to the web application, post a request and listen for the response.
public MyResponse postRequest(MyRequest myRequest) { try { // Open the connection URL url = new URL(getCodeBase(), "myServlet"); URLConnection uc = url.openConnection(); // Post the request uc.setDoOutput(true); uc.setDoInput(true); uc.setUseCaches(false); uc.setRequestProperty("Content-type", "java-internal/" + myRequest.getClass().getName()); ObjectOutputStream out = new ObjectOutputStream(uc.getOutputStream()); out.writeObject(myRequest); out.flush(); // Read the response ObjectInputStream in = new ObjectInputStream(uc.getInputStream()); return (MyResponse) in.readObject(); } catch (Exception e) { e.printStackTrace(); } return null; }
The servlet that handles the post would be pretty simple too. It just needs to read the request, figure out what the request was and return the correct data.
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { try { // Read the resquest ObjectInputStream ois = new ObjectInputStream(req.getInputStream()); MyRequest myRequest = (MyRequest) ois.readObject(); // Format the response from the session data HttpSession session = req.getSession(true); MyResponse myResponse = new MyResponse(session.fooData); // Send the response ObjectOutputStream oos = new ObjectOutputStream(res.getOutputStream()); oos.writeObject(myResponse); } catch (Exception e) { e.printStackTrace(); } }