By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,595 Members | 3,721 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,595 IT Pros & Developers. It's quick & easy.

Javascript-Applet-Servlet Comunication

P: 4
Hi, a few (3) questions for the Java experts, and let me know if this is the right forum. It deals with 100% java code (reason for posting here) but manages a Web browser with Javascript. Thanks in advance for responding. I have made a stub of the codes for better understanding.

Situation: I have a Java servlet (HelloWorldServlet) running on a Tomcat (5.5.26) server on a Linux machine (compiled in JDK1.4.2). It writes Javascript to construct a framed webpage. A frame in there contains an applet (HelloWorldApplet) using Swing, which implements ActionListener. On some ActionEvent, the applet invokes the (same) Servlet, grabs its output, and tries to write out a web page. The web browser is MSIE 7.0 on Windows XP. The code below (2 files) is complete, and is compiled with the script shown below. The servlet generates different html/javascript outputs based on whether doGet() or doPost() is used, and the parameters sent to it.

Question 1: Refer to the Servlet code (lines 50 and 73)
Output from the method printIndexHtml() is (a) Used directly by the servlet to write out the web page, and (b) captured by the applet to write out a webpage using javascript:document.write() function. If the # sign is put in front of the color code, (a) works, but (b) doesnt - apparently the # is treated by javascript as a syntax error, but only in (b). On line 75, the servlet uses a similar javascript command, and this time it works. Why is it not working in case (b) ?

Question 2. Refer to the Applet code (line 74)
Essentially, the applet is getting a new name from the user, and using it the rewrite the web page using the same servlet (getServletPostResponse()) with its doPost() method. I can set the target to "_blank" to open a new browser page (on Firefox I get a new tab), but not "_self" to overwrite contents of the existing page, with the javascript:document.write() function. Why, and how can I make "_self" work?

Question 3. Manipulation of browser navigation field
The web document is a frameset with 2 frames, and the contents for both of them is generated by the servlet. The browser should display "...:8080/hw/hw" on the navigation field, which it does correctly during initialization. However, when I get the applet to write out a web page on a new window, the navigation field of this new window displays the http address of the 2nd frame from the previous window. How can I fix this?

There, I hope the questions make sense. Again, thanks for your help.

Expand|Select|Wrap|Line Numbers
  1. #!/bin/csh -f
  2. #Compile the servlet, resulting jar will also act as the applet archive
  3. #this file is in directory .../webapps/hw/WEB-INF/classes/
  4. setenv TOMCATDIR /homes/tomcat/apache-tomcat-5.5.26
  5. setenv CLASSPATH $TOMCATDIR/common/lib/servlet-api.jar:$CLASSPATH
  6. javac hw/*.java && jar cvf ../../hw.jar hw/*.class && \
  7.             (echo; echo -n "Java archive hw.jar built by `whoami` on "; date)
  8.  
Source Code for the Servlet:

Expand|Select|Wrap|Line Numbers
  1. package hw;
  2.  
  3. import java.io.*;
  4. import javax.servlet.*;
  5. import javax.servlet.http.*;
  6.  
  7. public class HelloWorldServlet extends HttpServlet {
  8.         protected       int             serverPort = 8080;
  9.         protected       String          uNameIdentifier =
  10.                                         HelloWorldApplet.userNameIdentifier,
  11.                                         method, hostServer = "<insertHostNameHere>";
  12.  
  13.         public void doGet (HttpServletRequest req, HttpServletResponse res)
  14.                                                 throws ServletException, IOException {
  15.                 String reqURL = req.getQueryString();
  16.                 res.setContentType ("text/html");
  17.                 PrintWriter out = res.getWriter();
  18.                 method = "get";
  19.  
  20.                 if (reqURL == null || reqURL.length() <= 0)
  21.                         printIndexHtml (out, "");
  22.                 else if (reqURL.startsWith (uNameIdentifier + "="))
  23.                         printJavaScriptToRunApplet (out, reqURL.substring (1 +
  24.                                                 uNameIdentifier.length()));
  25.                 else
  26.                         out.println ("Servlet Error: Do not recognize<br>" + reqURL);
  27.                 out.close();
  28.         }
  29.  
  30.         public void doPost (HttpServletRequest req, HttpServletResponse res)
  31.                                 throws ServletException, IOException {
  32.                 String[] parValues = req.getParameterValues (uNameIdentifier);
  33.                 if (parValues == null || parValues.length < 2) {
  34.                         doGet (req, res);
  35.                 } else {
  36.                         method = "post";
  37.                         String userName = parValues[1];
  38.                         res.setContentType ("text/html");
  39.                         PrintWriter out = res.getWriter();
  40.                         if (userName == null || userName.length() <= 0)
  41.                                 out.println ("Post Error: userName not found");
  42.                         else
  43.                                 printIndexHtml (out, userName);
  44.                         out.close();
  45.         }}
  46.  
  47.         private void printIndexHtml (PrintWriter out, String name) {
  48.                 String appletURLstr = "http://" + hostServer + ":" +
  49.                                 serverPort + "/hw/hw?" + uNameIdentifier + "=" + name,
  50.                     // titleHtml = "<body bgcolor=#b3956d>"  + 
  51.                     // above will fail when applet writes it, because of #
  52.                     titleHtml = "<body bgcolor=b3956d>" +
  53.                                 "<p><center><font shape=arial size=6 color=ffffff>" +
  54.                         "Hello, " + ((name.length()>0) ? name : "World")+" ("+method+")"+
  55.                         "</font><br><font shape=arial size=5 color=ffffff>" +
  56.                         "Applet-Servlet Communication Tester</font></center></body>";
  57.  
  58.                 out.println ("<html><head><title>Hello World ("+method+")</title>");
  59.                 out.println ("</head><frameset border=0 frameborder=0 " +
  60.                                         "framespacing=0 rows=\"100,*\">");
  61.                 out.println ("<frame src=\"javascript:document.write('" + titleHtml +
  62.                                                 "')\" noresize scrolling=\"no\">");
  63.                 out.println ("<frame src=\""+ appletURLstr +"\" noresize scrolling=\"no\">");
  64.                 out.println ("</frameset></html>");
  65.         }
  66.  
  67. private void printJavaScriptToRunApplet (PrintWriter out, String userName) {
  68.             String parStr = "";
  69.             if (userName != null && userName.length() > 0)
  70.                 parStr = "'<param name=" + uNameIdentifier + " value="+userName+"> ' +\n";
  71.             out.println ("<html><head><script type=\"text/javascript\">\n" +
  72.                 "function startHelloWorldApplet() {\n" +
  73.                 "  document.write('<html><body bgcolor=#ffffff>' +\n" +        // this works
  74.                 "                '<p><p><center><applet archive= \"hw.jar\" ' +\n" +
  75.                 "                'code = \"hw/HelloWorldApplet.class\" ' +\n" +
  76.                 "                'width=400 height=200> ' +\n" + parStr +
  77.                 "                '</applet></center></body></html>');\n" +
  78.                 "}\n" +
  79.                 "</script></head><body onload=\"startHelloWorldApplet()\"></body></html>");
  80. }}
  81.  
Source Code for the Applet

Expand|Select|Wrap|Line Numbers
  1. package hw;
  2.  
  3. import java.io.*;
  4. import java.awt.*;
  5. import java.net.*;
  6. import java.util.*;
  7. import java.applet.*;
  8. import javax.swing.*;
  9. import java.awt.event.*;
  10.  
  11. public class HelloWorldApplet extends JApplet implements ActionListener {
  12.  
  13.         protected URL        appletURL;
  14.         protected AppletContext    appletContext;
  15.         protected JTextField     userNameField = new JTextField(10);
  16.         protected static        String    userNameIdentifier = "userName";
  17.         private            String    currentUserName = "World";
  18.  
  19.         public void start () { }
  20.         public void stop () { }
  21.         public void destroy () { }
  22.         public void paint (Graphics g) { super.paint (g); }
  23.  
  24.         public void init () {
  25.             String userName = getParameter (userNameIdentifier);
  26.             if (userName != null && userName.length() > 0)
  27.                 currentUserName = userName;
  28.             appletURL = getDocumentBase();
  29.             appletContext = getAppletContext();
  30.                 try {
  31.                         SwingUtilities.invokeAndWait (new Runnable () {
  32.                                 public void run () {
  33.                                         createGUI();
  34.                         }});
  35.                 } catch (Exception ex) {
  36.                         JOptionPane.showMessageDialog (new JFrame(),
  37.                                         ex.getMessage());
  38.         }}
  39.  
  40.         public void createGUI () {
  41.                 Container cp = getContentPane();
  42.                 cp.setLayout (new BorderLayout());
  43.  
  44.             JButton postButton = new JButton ("Post It");
  45.             postButton.addActionListener (this);
  46.             userNameField.addActionListener (this);
  47.  
  48.                 JPanel        np = new JPanel(), bp = new JPanel(),
  49.                 qp = new JPanel(), tp = new JPanel();
  50.  
  51.                 np.add (new JLabel ("Have a great day, " + currentUserName));
  52.             qp.add (new JLabel ("Username to greet next:"));
  53.             tp.add (userNameField);
  54.             bp.add (postButton);
  55.                 bp.setBackground (Color.white);
  56.                 np.setBackground (Color.white);
  57.  
  58.                 cp.add (np, "North");
  59.                 cp.add (qp, "West");
  60.                 cp.add (tp, "Center");
  61.                 cp.add (bp, "South");
  62.                 cp.setBackground (Color.white);
  63.         }
  64.  
  65.         public void actionPerformed (ActionEvent e) {
  66.             String uName = userNameField.getText();
  67.             if (uName.length() <= 0) {
  68.                 JOptionPane.showMessageDialog (new JFrame(),
  69.                                 "Please enter the next username to greet",
  70.                                 "Missing User Name", JOptionPane.ERROR_MESSAGE);
  71.                 return;
  72.             } else {
  73.                 try {
  74.                     String     target = // "_self", // does not work
  75.                              "_blank",
  76.                         servletResponse = getServletPostResponse (uName);
  77.                     appletContext.showDocument (new URL (
  78.                         "javascript:document.write('"+ servletResponse+"')"),
  79.                                         target);
  80.                 } catch (Exception ex) {
  81.         }}}
  82.  
  83. private String getServletPostResponse (String userName) throws Exception {
  84.             URLConnection urlc = appletURL.openConnection();
  85.                 if (urlc instanceof HttpURLConnection)
  86.                         ((HttpURLConnection) urlc).setRequestMethod("POST");
  87.                 else
  88.                         throw new Exception ("URL connection is not Http");
  89.  
  90.                 urlc.setUseCaches (false);
  91.                 urlc.setDefaultUseCaches (false);
  92.                 urlc.setDoInput (true);
  93.                 urlc.setDoOutput (true);
  94.                 urlc.setRequestProperty ("Content-type", "application/x-www-form-urlencoded");
  95.  
  96.                 urlc.connect();
  97.             DataOutputStream out = new DataOutputStream (urlc.getOutputStream());
  98.  
  99.                 String postContents = userNameIdentifier + "=" + userName;
  100.                 out.writeBytes (postContents);
  101.                 out.flush();
  102.                 out.close();
  103.  
  104.                 BufferedReader br = new BufferedReader (new InputStreamReader (
  105.                                 urlc.getInputStream()));
  106.                 String httpOutput = "";
  107.                 for (String s = br.readLine() ; s != null ; s = br.readLine())
  108.                         httpOutput += s ;
  109.  
  110.                 br.close();
  111.             // Replace all "'" by "\'"
  112.                 StringTokenizer st = new StringTokenizer (httpOutput, "'");
  113.                 httpOutput = st.nextToken();
  114.                 while (st.hasMoreTokens())
  115.                         httpOutput += "\\'" + st.nextToken();
  116.                 return httpOutput;
  117. }}
  118.  
Sep 23 '08 #1
Share this Question
Share on Google+
2 Replies


10K+
P: 13,264
I think all these questions are more web related than Java related so I'll move to the Javascript forum for now.
Sep 23 '08 #2

acoder
Expert Mod 15k+
P: 16,027
For the first question, you're setting the src of the frame. That should be to a file, not some HTML code.
Sep 23 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.