要在SSH项目中执行异步提交,需要使用JSON返回页面的JSON字符串
XXXAction将DAO通过查询返回的List集合转换为JSONArray数组
通常如下。
java代码:
list list=book服务. find all (; //所有查询返回book的List集合结果
jsonarrayjsonarray=JSON array.from object (列表; 将列表更改为JSONArray
String json=jsonArray.toString (; //json字符串
servletactioncontext.getresponse (.set content type (' text/html; charset=utf-8 '; //更改代码
printwriter out=servletactioncontext.getresponse ().getWriter ); 获取PrintWriter对象
out.print(JSON; 返回json字符串的页面
另一方面,如果项目中的多个表具有主键关系,也就是说,hibernate映射具有一对多或多对一的关系。
实体类在“多”侧具有“一”侧实体对象,在“一”侧具有“多”侧Set集合。
如果查询返回List对象并将其转换为JSONArray,则上述代码报告错误。
解决方案——过滤查询中的实体对象或Set集合:
java代码:
list list=book服务. find all (; //所有查询返回book的List集合结果
JsonConfig config=new JsonConfig (;
config.set excludes (new string [ ] { ' category ' }; //红色部分不会过滤Category对象并将其转换为JSONArray
jsonarrayjsonarray=JSON array.from object (list,config );
String json=jsonArray.toString (; //json字符串
servletactioncontext.getresponse (.set content type (' text/html; charset=utf-8 '; //更改代码
printwriter out=servletactioncontext.getresponse ().getWriter ); 获取PrintWriter对象
out.print(JSON; 返回json字符串的页面
过滤后不会报告有实体的对象,但页面上需要类似于类型表的名称,如果你不能过滤名为Category的对象并获取类型名称,就会很为难。 于是老师看了帮助文档后,教了我别的方法。
java代码:
list list=book服务. find all (; //所有查询返回book的List集合结果
JsonConfig config=new JsonConfig (;
config.setcycledetectionstrategy (cycledetectionstrategy.lenient );
jsonarrayjsonarray=JSON array.from object (list,config );
String json=jsonArray.toString (; //json字符串
servletactioncontext.getresponse (.set content type (' text/html; charset=utf-8 '; //更改代码
printwriter out=servletactioncontext.getresponse ().getWriter ); 获取PrintWriter对象
out.print(JSON; 返回json字符串的页面
调查“多”的一方和调查“一”的一方现在都可以用上述代码解决。
但是,“较多”的映射文件的many-to-one元素必须具有lazy='false ' (无延迟加载)的属性。 不然我还是报告错误。