Struts2 返回JSON数据方法(二)使用JSONObject
这种方式需要在action中用到Response。但是我有一个疑问,在struts2的action中用到response好吗?是不是应尽量不用?
需要导入的jar包ezmorph-1.0.6.jar
action代码:
public class LoginAction extends ActionSuppor{ //将要被Struts2序列化为JSON字符串的对象 Map<String, Object> message; public Map<String, Object> getMessage() { return message; } public void setMessage(Map<String, Object> message) { this.message = message; } //验证登陆 public String loginTch() { message = new HashMap<String, Object>();
//省略用户名密码的判断...... message.put("loginError", "密码错误!"); //将封装的信息转成JSON数据传入前台 PrintWriter writer; HttpServletResponse response = ServletActionContext.getResponse(); response.setCharacterEncoding("UTF-8"); try { writer = response.getWriter();//将内容输出到response String json = YHJSONUtil.serialize(message); writer.write(json); writer.close(); } catch (IOException e) { e.printStackTrace(); } } return SUCCESS; }
jsp页面代码:
<head> <script src="js/jquery.js" type="text/javascript"></script> <script type="text/javascript"> function doSubmit() { $.ajax({ type: "GET", url: "loginAction", dataType: "json", cache: false, success: function(data) { $.each(data, function(key, val) { if (key == "loginError" && val != ''){ $("#mes").html(val); return false; } }); } }); } </script> </head> <body> <div id="mes"> </div>
<!-- 省去用户名密码输入 --> <button type="button" onlick="doSubmit()">提交</button> </body>
不需要在struts.xml中配置