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