html页面怎么调用java方法

如题所述

在html页面中,使用js调用java类要使用ajax,具体方法步骤如下:
1、将要调用的类名和方法名作为参数传给某个servlet.这一步的方法有许多种,用框架,或者直接用xmlHttpRequest对象;
2、要调用的类名和类的完整包路径最好写在配置文件里,这里假设类名为Hello,方法名为sayHello,并且sayHello方法不带参数,类路径为com.demo.Hello。
3、配置文件AjaxConfig.properties
Hello = com.demo.Hello
4、传入的参数设置为 class=Hello&method=sayHello
在servlet中作如下处理:
String className=request.getParameter("classname");
String methodName=request.getParameter("method");
String classPath=null;
5、读取配置文件,取出className所对应的值放入classPath变量中,
Class c=Class.forName(classPath);//加载你所指定的类
Class param[]=new Class[0];//方法的参数为0个
Method m=null;
String returnValue=null;//返回值
try {
m = c.getMethod("sayHello",param);//获取你所指定的类中的指定方法
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

try {
returnValue=(String)m.invoke(c.newInstance(), new Object[0]);//调用你所指定的方法
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InstantiationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
6、将returnValue的值返回给客户端即可
类Hello.java

public class Hello
{
public String sayHello()
{
return "hello";
}
}
温馨提示:答案为网友推荐,仅供参考