使用java作为后端将javascript连接到java

时间:2016-06-14 06:51:55

标签: javascript java html applet

我正在尝试使用html,javascript和java的简单Web应用程序。 HTML和javascript是前端的一部分,java构成了后端。我正在使用小程序。我不想使用JSP或JSF,因为我当前的要求说我只需要使用HTML和javascript。我收到以下错误。

enter image description here

我从在线资源获得此代码。我的代码如下:

HTML:

 <script type="text/javascript" src="liveconnect.js"> </script>
 </head>
 <body onload="showProgrammer()">
   <applet id="app" code="LauncherApplet" height="1" width="1" MAYSCRIPT></applet> 
   <table>
    <tr>
     <td>Name</td>
     <td>:</td>
    <td><input type="text" id="name"/></td>
  </tr>
    <td>Age</td>
    <td>:</td>
    <td><input type="text" id="age"/></td>
  </tr>
    <td>Programming Language(PHP,Java or Python)</td>
    <td>:</td>
    <td><input type="text" id="language"/></td>
  </tr>
 </table>
 <input type="button" onclick="processProgrammer()" value="click"/>
</body>

JS:

function Programmer(name,age,language){
  this.name=name;
  this.age=age;
  this.language=language;
 }
 function showProgrammer(){
 try{
   var programmer=app.getProgrammer(); //app is the id of applet tag which refers to the applet instance.
   var data="Name= "+programmer.name+",Age= "+programmer.age+",Language= "+programmer.language;
   alert(data);
 }
 catch(e){
   alert(e);
  }
 }
 function processProgrammer(){
 try{
   var name=document.getElementById("name").value;
   var age=document.getElementById("age").value;
   var language=document.getElementById("language").value;
   var programmer=app.getProgrammer();
   var myprog=new Programmer(name,age,language);
   programmer.setData(myprog);
   var advice=programmer.getAdvice();
   alert(advice);
  }
  catch(e){
   alert(e);
  }
 }

小程序:

import java.applet.*;
import java.awt.*;
public class LauncherApplet extends Applet{
  public Programmer getProgrammer(){
    return new Programmer();
 }

}

主java文件:

import netscape.javascript.*;
public class Programmer {
  public String name="Programmer1";
  public String age="20";
  public String language="Java";
  public void setData(JSObject js){
  try{
    this.name=((String)js.getMember("name")).toLowerCase();
    this.age=((String)js.getMember("age")).toLowerCase();
    this.language=((String)js.getMember("language")).toLowerCase();
    System.out.println("Name= "+name+",Age= "+age+",language= "+language);
 }
 catch(JSException e){System.out.println(e);}
}
public String getAdvice(){
  String advice="";
  switch(language){
   case "php":
     advice=name+", you should definitely try out CodeIgniter.";
     break;
   case "java":
     advice=name+", you should definitely try out JavaServer Faces.";
     break;
   case "python":
     advice=name+", you should definitely try out Django.";
     break;
   default:
     advice="You language of choice is not any one of PHP, Java or Python";
  }
  return advice;
 }
}

java文件已成功编译。没有错误。请告诉我我犯了什么错误。

提前致谢

1 个答案:

答案 0 :(得分:-1)

您可以使用DWR(直接Web路由)技术。这只是一个Ajax函数..

http://directwebremoting.org/dwr/introduction/getting-started.html

这可能对你有帮助。