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;
}

}


猜你喜欢

转载自blog.csdn.net/qq_25717027/article/details/75339435