ajax调用java方法
ajax调用java后台的方法,其实是通过url链接来访问。下面是学习啦小编为大家带来一篇ajax调用java方法,希望对大家有所帮助。
ajax调用java方法(一)
public void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException,java.io.IOException{
//得到类名、方法名和参数
String methodName=req.getParameter("methodName");
String className=req.getParameter("className");
Object[] objs=req.getParameterValues("params");
Object targetObj;
try {
targetObj = Class.forName(className).newInstance();
Object obj=MethodUtils.invokeMethod(targetObj, methodName, objs);
this.dealResp(resp, obj);
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private void dealResp(HttpServletResponse resp,Object obj) throws IOException{
resp.setContentType("text/xml;charset=GBK");
PrintWriter pw=resp.getWriter();
pw.write(""+deal(obj)+"");
pw.flush();
pw.close();
}
private String deal(Object obj){
String sbResult="";
if(obj==null){
sbResult="";
}else if(obj instanceof java.lang.String){
sbResult=dealString(obj);
}else if(obj instanceof java.util.List){
sbResult=dealList(obj);
}else if(obj instanceof java.lang.Boolean){
sbResult=dealBoolean(obj);
}else if(obj instanceof java.lang.Double){
sbResult=dealDouble(obj);
}else if((obj instanceof java.lang.Integer) || (obj instanceof java.lang.Long)){
sbResult=dealInteger(obj);
}else if(obj instanceof java.lang.Throwable){
sbResult=dealException(obj);
}else if(obj instanceof java.util.Map){
sbResult=dealMap(obj);
}else if(obj instanceof java.util.Date){
sbResult=dealDate(obj);
}else if(obj instanceof java.util.Calendar){
sbResult=dealDate(obj);
}else if(obj instanceof org.w3c.dom.Document){
sbResult=dealXml(obj);
}else{
sbResult=dealObject(obj);
}
return sbResult;
}
//处理Date或Calendar类型,返回值为yyyy-MM-dd-HH-mm-ss-SSS格式的字符串
private String dealDate(Object obj){
Calendar cal=null;
if(obj instanceof Calendar){
cal=(Calendar)obj;
}else{
cal=Calendar.getInstance();
cal.setTime((Date)obj);
}
StringBuffer sb=new StringBuffer();
sb.append("");
sb.append(cal.get(Calendar.YEAR));
sb.append("-");
sb.append(cal.get(Calendar.MONTH));
sb.append("-");
sb.append(cal.get(Calendar.DAY_OF_MONTH));
sb.append("-");
sb.append(cal.get(Calendar.HOUR_OF_DAY));
sb.append("-");
sb.append(cal.get(Calendar.MINUTE));
sb.append("-");
sb.append(cal.get(Calendar.SECOND));
sb.append("-");
sb.append(cal.get(Calendar.MILLISECOND));
sb.append("");
return sb.toString();
}
private String dealMap(Object obj){
StringBuffer sb=new StringBuffer();
Map map=(Map)obj;
sb.append("");
Set entrys=map.entrySet();
Iterator ite=entrys.iterator();
Map.Entry entry=null;
while(ite.hasNext()){
entry=(Map.Entry)ite.next();
sb.append("<");
sb.append(entry.getKey());
sb.append(">");
sb.append(deal(entry.getValue()));
sb.append(");
sb.append(entry.getKey());
sb.append(">");
}
sb.append("");
return sb.toString();
}
ajax调用java方法(二)
public class Test {
public static String sayHello(String name){
return "hello, " + name;
}
}
注意:必须是公开的静态方法。
ajax分为同步、异步调用,如果没有传递回调函数,则是同步调用;如果传递回调函数,则是异步调用。
同步调用
<script type="text/javascript">
......
try{
var obj = Test.sayHello('world!');
......
}catch(e){
//e.error 错误码
//e.message 错误描述
}
......
</script>
不传递回调函数,以try…catch来处理错误。在同步调用模式下,如果有网络错误、业务逻辑错误等,会抛出一个异常。
异步调用
<script type="text/javascript">
......
Test.sayHello('world!',
function(obj){ //success callback function
......
},
function(error, message){ //fail callback function
}
);
......
</script>
传递回调函数作为参数。如果只有一个回调函数, 则默认是成功的回调函数。
AJAXRPC完整示例
首先我们有一个服务端的类,和一些静态方法:
public class Test {
//test Date
public static Date getTime(){
return new Date();
}
//test Number
public static int add(int a, int b){
return a + b;
}
//test String
public static String sayHello(String name){
return "hello, " + name;
}
//test Boolean
public static Boolean isTrue(Boolean b){
return b == true;
}
//test Object
public static String addUser(Map user){
String id = UUID.randomUUID().toString();
user.put("id", id);
//insert to database
//...
return id;
}
//test Array
public static List getUsers(String name){
List users = new ArrayList();
for(int i=0; i<20; i++){
Map user = new HashMap();
user.put("name", name+i);
user.put("gender", i%2);
user.put("birthday", new Date());
users.add(user);
}
return users;
}
//test user defined class
public static User updateUser(User user)
{
user.birthday = new Date();
//update to database...
return user;
}
//test user defined class array
public static User[] saveUsers(User[] users)
{
for (int i = 0, l = users.length; i < l; i++)
{
User user = users[i];
user.name = "Server" + i;
user.birthday = new Date();
//update to database...
}
return users;
}
}