Last Updated on 09 August 2019   |   Print Email
There would be some cases in which we need to submit an HTML form from within a Java applet. The applet does some tasks and then needs to submit the form in the enclosing HTML page. To do so, we would utilize the capability of communication between Java applet and Javascript through the LiveConnect technology as follows:
In the HTML page, write a Javascript function that contains code to submit the form. For example:
function submitForm() {
// do some processing submit the form...
document.forms[0].submit();
}
That will submit the first form in the HTML document.
In the applet, invoke the Javascript’s submitForm() function like this:
That passes two String arguments “param1” and “param2” to the Javascript method. Following is complete code of the sample HTML page:
<html>
<head>
<title>Submitting HTML form in Java applet</title>
</head>
<body>
<center>
<!-- show the applet -->
<applet id="SampleApplet"
code="SampleApplet.class"
width="200" height="50"
>
</applet>
<!-- show HTML form -->
<form method="POST" action="http://localhost:8080/SampleApp/process">
Enter Full Name: <input type="text" name="fullname" size="30"/>
<br/>
Enter E-mail: <input type="text" name="email" size="30"/>
</form>
</center>
</body>
<script type="text/javascript">
function submitForm() {
// do some processing submit the form...
document.forms[0].submit();
}
</script>
</html>
This HTML page displays a Java applet with only a button, along with an HTML form with two text fields.
And here is complete code of the sample applet:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import netscape.javascript.*;
/**
* A sample Java applet that demonstrates how to call Javascript in order to
* submit the form in the enclosing HTML page.
*/
public class SampleApplet extends JApplet {
private JButton button = new JButton("Submit");
public void init() {
getContentPane().setLayout(new FlowLayout());
getContentPane().add(button);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
buttonActionPerformed(evt);
}
});
}
public void buttonActionPerformed(ActionEvent evt) {
try {
JSObject jsObj = JSObject.getWindow(this);
jsObj.call("submitForm", null);
} catch (JSException ex) {
ex.printStackTrace();
}
}
}
This applet simply displays a button which will invoke the Javascript function when clicked.Opening the page SampleAppletTest.html in browser:Click the Submit button, values of the two text fields in the form will be submitted to the URL specified by the action attribute of <form> element.
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Comments
Chrome còn thiếu setting gì không anh?