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
- #!/bin/csh -f
- #Compile the servlet, resulting jar will also act as the applet archive
- #this file is in directory .../webapps/hw/WEB-INF/classes/
- setenv TOMCATDIR /homes/tomcat/apache-tomcat-5.5.26
- setenv CLASSPATH $TOMCATDIR/common/lib/servlet-api.jar:$CLASSPATH
- javac hw/*.java && jar cvf ../../hw.jar hw/*.class && \
- (echo; echo -n "Java archive hw.jar built by `whoami` on "; date)
Expand|Select|Wrap|Line Numbers
- package hw;
- import java.io.*;
- import javax.servlet.*;
- import javax.servlet.http.*;
- public class HelloWorldServlet extends HttpServlet {
- protected int serverPort = 8080;
- protected String uNameIdentifier =
- HelloWorldApplet.userNameIdentifier,
- method, hostServer = "<insertHostNameHere>";
- public void doGet (HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- String reqURL = req.getQueryString();
- res.setContentType ("text/html");
- PrintWriter out = res.getWriter();
- method = "get";
- if (reqURL == null || reqURL.length() <= 0)
- printIndexHtml (out, "");
- else if (reqURL.startsWith (uNameIdentifier + "="))
- printJavaScriptToRunApplet (out, reqURL.substring (1 +
- uNameIdentifier.length()));
- else
- out.println ("Servlet Error: Do not recognize<br>" + reqURL);
- out.close();
- }
- public void doPost (HttpServletRequest req, HttpServletResponse res)
- throws ServletException, IOException {
- String[] parValues = req.getParameterValues (uNameIdentifier);
- if (parValues == null || parValues.length < 2) {
- doGet (req, res);
- } else {
- method = "post";
- String userName = parValues[1];
- res.setContentType ("text/html");
- PrintWriter out = res.getWriter();
- if (userName == null || userName.length() <= 0)
- out.println ("Post Error: userName not found");
- else
- printIndexHtml (out, userName);
- out.close();
- }}
- private void printIndexHtml (PrintWriter out, String name) {
- String appletURLstr = "http://" + hostServer + ":" +
- serverPort + "/hw/hw?" + uNameIdentifier + "=" + name,
- // titleHtml = "<body bgcolor=#b3956d>" +
- // above will fail when applet writes it, because of #
- titleHtml = "<body bgcolor=b3956d>" +
- "<p><center><font shape=arial size=6 color=ffffff>" +
- "Hello, " + ((name.length()>0) ? name : "World")+" ("+method+")"+
- "</font><br><font shape=arial size=5 color=ffffff>" +
- "Applet-Servlet Communication Tester</font></center></body>";
- out.println ("<html><head><title>Hello World ("+method+")</title>");
- out.println ("</head><frameset border=0 frameborder=0 " +
- "framespacing=0 rows=\"100,*\">");
- out.println ("<frame src=\"javascript:document.write('" + titleHtml +
- "')\" noresize scrolling=\"no\">");
- out.println ("<frame src=\""+ appletURLstr +"\" noresize scrolling=\"no\">");
- out.println ("</frameset></html>");
- }
- private void printJavaScriptToRunApplet (PrintWriter out, String userName) {
- String parStr = "";
- if (userName != null && userName.length() > 0)
- parStr = "'<param name=" + uNameIdentifier + " value="+userName+"> ' +\n";
- out.println ("<html><head><script type=\"text/javascript\">\n" +
- "function startHelloWorldApplet() {\n" +
- " document.write('<html><body bgcolor=#ffffff>' +\n" + // this works
- " '<p><p><center><applet archive= \"hw.jar\" ' +\n" +
- " 'code = \"hw/HelloWorldApplet.class\" ' +\n" +
- " 'width=400 height=200> ' +\n" + parStr +
- " '</applet></center></body></html>');\n" +
- "}\n" +
- "</script></head><body onload=\"startHelloWorldApplet()\"></body></html>");
- }}
Expand|Select|Wrap|Line Numbers
- package hw;
- import java.io.*;
- import java.awt.*;
- import java.net.*;
- import java.util.*;
- import java.applet.*;
- import javax.swing.*;
- import java.awt.event.*;
- public class HelloWorldApplet extends JApplet implements ActionListener {
- protected URL appletURL;
- protected AppletContext appletContext;
- protected JTextField userNameField = new JTextField(10);
- protected static String userNameIdentifier = "userName";
- private String currentUserName = "World";
- public void start () { }
- public void stop () { }
- public void destroy () { }
- public void paint (Graphics g) { super.paint (g); }
- public void init () {
- String userName = getParameter (userNameIdentifier);
- if (userName != null && userName.length() > 0)
- currentUserName = userName;
- appletURL = getDocumentBase();
- appletContext = getAppletContext();
- try {
- SwingUtilities.invokeAndWait (new Runnable () {
- public void run () {
- createGUI();
- }});
- } catch (Exception ex) {
- JOptionPane.showMessageDialog (new JFrame(),
- ex.getMessage());
- }}
- public void createGUI () {
- Container cp = getContentPane();
- cp.setLayout (new BorderLayout());
- JButton postButton = new JButton ("Post It");
- postButton.addActionListener (this);
- userNameField.addActionListener (this);
- JPanel np = new JPanel(), bp = new JPanel(),
- qp = new JPanel(), tp = new JPanel();
- np.add (new JLabel ("Have a great day, " + currentUserName));
- qp.add (new JLabel ("Username to greet next:"));
- tp.add (userNameField);
- bp.add (postButton);
- bp.setBackground (Color.white);
- np.setBackground (Color.white);
- cp.add (np, "North");
- cp.add (qp, "West");
- cp.add (tp, "Center");
- cp.add (bp, "South");
- cp.setBackground (Color.white);
- }
- public void actionPerformed (ActionEvent e) {
- String uName = userNameField.getText();
- if (uName.length() <= 0) {
- JOptionPane.showMessageDialog (new JFrame(),
- "Please enter the next username to greet",
- "Missing User Name", JOptionPane.ERROR_MESSAGE);
- return;
- } else {
- try {
- String target = // "_self", // does not work
- "_blank",
- servletResponse = getServletPostResponse (uName);
- appletContext.showDocument (new URL (
- "javascript:document.write('"+ servletResponse+"')"),
- target);
- } catch (Exception ex) {
- }}}
- private String getServletPostResponse (String userName) throws Exception {
- URLConnection urlc = appletURL.openConnection();
- if (urlc instanceof HttpURLConnection)
- ((HttpURLConnection) urlc).setRequestMethod("POST");
- else
- throw new Exception ("URL connection is not Http");
- urlc.setUseCaches (false);
- urlc.setDefaultUseCaches (false);
- urlc.setDoInput (true);
- urlc.setDoOutput (true);
- urlc.setRequestProperty ("Content-type", "application/x-www-form-urlencoded");
- urlc.connect();
- DataOutputStream out = new DataOutputStream (urlc.getOutputStream());
- String postContents = userNameIdentifier + "=" + userName;
- out.writeBytes (postContents);
- out.flush();
- out.close();
- BufferedReader br = new BufferedReader (new InputStreamReader (
- urlc.getInputStream()));
- String httpOutput = "";
- for (String s = br.readLine() ; s != null ; s = br.readLine())
- httpOutput += s ;
- br.close();
- // Replace all "'" by "\'"
- StringTokenizer st = new StringTokenizer (httpOutput, "'");
- httpOutput = st.nextToken();
- while (st.hasMoreTokens())
- httpOutput += "\\'" + st.nextToken();
- return httpOutput;
- }}