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?

Pete Lyons

The easiest way to pass session info is through the applet parameters. The following example code uses some scriptlet tags to set the parameters of the applet.

<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) %>">
<% } %>

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
                  "java-internal/" + 
		ObjectOutputStream out = 
                  new ObjectOutputStream(uc.getOutputStream());

		// Read the response
		ObjectInputStream in =	
                  new ObjectInputStream(uc.getInputStream());
		return (MyResponse) in.readObject();
	} catch (Exception e) {
	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());
	} catch (Exception e) {
0 Comments  (click to add your comment)
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



About | Sitemap | Contact