ajax調(diào)用java方法
ajax調(diào)用java后臺(tái)的方法,其實(shí)是通過(guò)url鏈接來(lái)訪問(wèn)。下面是學(xué)習(xí)啦小編為大家?guī)?lái)一篇ajax調(diào)用java方法,希望對(duì)大家有所幫助。
ajax調(diào)用java方法(一)
public void doPost(HttpServletRequest req, HttpServletResponse resp) throwsServletException,java.io.IOException{
//得到類名、方法名和參數(shù)
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調(diào)用java方法(二)
public class Test {
public static String sayHello(String name){
return "hello, " + name;
}
}
注意:必須是公開(kāi)的靜態(tài)方法。
ajax分為同步、異步調(diào)用,如果沒(méi)有傳遞回調(diào)函數(shù),則是同步調(diào)用;如果傳遞回調(diào)函數(shù),則是異步調(diào)用。
同步調(diào)用
<script type="text/javascript">
......
try{
var obj = Test.sayHello('world!');
......
}catch(e){
//e.error 錯(cuò)誤碼
//e.message 錯(cuò)誤描述
}
......
</script>
不傳遞回調(diào)函數(shù),以try…catch來(lái)處理錯(cuò)誤。在同步調(diào)用模式下,如果有網(wǎng)絡(luò)錯(cuò)誤、業(yè)務(wù)邏輯錯(cuò)誤等,會(huì)拋出一個(gè)異常。
異步調(diào)用
<script type="text/javascript">
......
Test.sayHello('world!',
function(obj){ //success callback function
......
},
function(error, message){ //fail callback function
}
);
......
</script>
傳遞回調(diào)函數(shù)作為參數(shù)。如果只有一個(gè)回調(diào)函數(shù), 則默認(rèn)是成功的回調(diào)函數(shù)。
AJAXRPC完整示例
首先我們有一個(gè)服務(wù)端的類,和一些靜態(tài)方法:
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;
}
}