ajax 与 json 在 jsp页面 ssh框架

前端之家收集整理的这篇文章主要介绍了ajax 与 json 在 jsp页面 ssh框架前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

1:需要导入的jar

commons-beanutils-1.8.3.jar

commons-collections-3.2.1

commons-lang-2.5

commons-logging-1.1.1

ezmorph-1.0.6

json-lib-2.3-jdk15

注意:如果导入导入了json-lib-2.3-jdk15但还报net.sf.json.JSONArray.class没找到的话,需要重新发布到tomcat

2:页面

<script type="text/javascript">
$(function(){
var loginUserId=${session.loginUser.id};
//新消息提醒
function message(){
$.ajax({
type: "POST",
url: "${pageContext.request.contextPath }/client/cMessageAction_show.action",
data:"loginUserId="+loginUserId+"",
dataType:"json",
success: function(msg){
alert( "Data Saved: "+msg[0].time);
},
error:function(){
alert("出错了");
}
});
}
if(loginUserId!=""){
setInterval(message,5000);
}
});
</script>

3:struts2端

List<Message> list=messageService.findAllMessage(loginUserId); //有级联,不能直接转化,要取出List放到map里面 JsonConfig cfg = new JsonConfig(); //过滤关联,避免死循环net.sf.json.JSONException: java.lang.reflect.InvocationTargetException cfg.setJsonPropertyFilter(new PropertyFilter() { public boolean apply(Object source,String name,Object value) { //把什么过滤掉 如属性为user的就不会放进json中 if(name.equals("user")||name.equals("id")) { System.out.println(name+"--"); return true; } else { System.out.println(name+"=="); return false; } } }); //net.sf.json.JSONException: java.lang.reflect.InvocationTargetException异常 cfg.setExcludes(new String[]{"handler","hibernateLazyInitializer"}); //javabean里出现循环调用啦,赶快用excludes干掉parent或者children // cfg.setExcludes(new String[]{"addressGroup"}); //net.sf.json.JSONException: java.lang.reflect.InvocationTargetException日期格式转化出错 cfg.setCycleDetectionStrategy(CycleDetectionStrategy.LENIENT); // cfg.registerJsonValueProcessor(Date.class,new DateJsonValueProcessor("yyyy-MM-dd hh:mm:ss")); JSONArray json=new JSONArray().fromObject(list,cfg); HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); if(out!=null){ out.print(json.toString()); out.flush(); out.close(); }

猜你在找的Ajax相关文章