1. 程式人生 > >struts2與springMvc下的AJax非同步資料互動1

struts2與springMvc下的AJax非同步資料互動1

                              struts2與springMvc下的AJax非同步資料互動1

  無論是在struts2還是springMvc框架下,Controller或者action均有2種json資料返回方法

1.在struts2下

 一.使用Servlet的輸出流

    JSON介面的實質是:JSON資料在傳遞過程中,其實就是傳遞一個普通的符合JSON語法格式的字串而已,所謂的“JSON物件”是指對這個JSON字串解析和包裝後的結果。

通過ServletActionContext ,獲取response。

response.setContentType("text/html;charset=utf-8");

//獲取輸出流

PrintWrite out=response.getWrite();

String msg="{\"user\":{\"id\":\"123\",\"name\":\"張三\"}";

out.print();

out.flush(msg);

out.close();

②使用Struts2對json的擴充套件( 用到的jar包 版本要匹配 xwork-2.1.2.jar和jsonplugin-0.34.jar

struts2.xml配置

<package name="json" extends="struts-default,json-default" namespace="/json">

<action name="testJson" action="userAction" mehtod="testJson">

<!---需要封裝為json格式的action 屬性,在action必須要有相應的getter方法-->

<param name="root"> map</param>

</action>

</package>

XXXXaction.java中

@Component("userAction")
@Scope("prototype")
public class UserAction extends ActionSupport {
    private  String userpw;
    private  Map<String,Object> map=null;

public String testJson(){

map=new HashMap<String,Object>();

User user=new User("123","張三");

map.put("user",user);

return " success";

}




public  Map<String,Object> getMap(){
return map;
}

@JSON(serialize=false)// 防止其被一起以json格式中返回
public String getUserpw() {
return userpw;
}

}