473,747 Members | 2,321 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Javascript-Applet-Servlet Comunication

4 New Member
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 (HelloWorldServ let) 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 (HelloWorldAppl et) 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:docu ment.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 (getServletPost Response()) 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:docu ment.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 3454
r035198x
13,262 MVP
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 Recognized Expert Moderator MVP
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
8979
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8818
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9355
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9307
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6790
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6069
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4860
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2773
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2203
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.