473,395 Members | 1,742 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Javascript-Applet-Servlet Comunication

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
2 3420
r035198x
13,262 8TB
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
16,027 Expert Mod 8TB
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

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

Similar topics

0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.