您的位置:首页 > 产品设计 > UI/UE

[SSH_easyUI]细节2:JSON

2015-05-12 22:58 218 查看

1. 后台数据用json方式返回前台的各种情况

1.1 Action中的方法

public void reg(){
String name = ServletActionContext.getRequest().getParameter("name");
String pwd = ServletActionContext.getRequest().getParameter("pwd");
String json= "";
try {
userService.add(name,pwd);
json = "{\"success\":true,\"msg\":\"注册成功\"}";
} catch (Exception e) {
e.printStackTrace();
json = "{\"success\":true,\"msg\":\"注册失败\"}";
}

try {
ServletActionContext.getResponse().setCharacterEncoding("utf-8");
ServletActionContext.getResponse().getWriter().write(json);//将json输出到前台
} catch (IOException e) {
e.printStackTrace();
}
}


1.2 index.jsp相对应代码

<div id="index_regDialog" class="easyui-dialog" style="width:250px;" data-options="title:'注册',closed:true,modal:true,closable:false,buttons:[{
text:'注册',
iconCls:'icon-edit',
handler:function(){ //这里是普通的form表单提交,但是写法是ajax的那种写法
regUser();
}
}]">
<form id="index_regForm" method="post">
<table>
<tr>
<th>用户名</th>
<td><input name="name" class="easyui-validatebox" data-options="required:true,missingMessage:'请输入用户名'" />
</td>
</tr>
<tr>
<th>密码</th>
<td><input name="pwd" class="easyui-validatebox" type="password" data-options="required:true,missingMessage:'请输入密码'" />
</td>
</tr>
<tr>
<th>重复密码</th>
<td><input name="rePwd" class="easyui-validatebox" type="password" data-options="required:true,missingMessage:'请输入确认密码',validType:'eqPwd[\'#index_regForm input[name=pwd]\']'" />
</td>
</tr>
</table>
</form>
</div>


1.3 分析

在后台传输标准格式的json数据到前台页面:但是因为双引号,转义比较麻烦

如:
json = "{\"success\":true,\"msg\":'注册成功'}";


在后台传输非标准的json数据到前台,前台通过eval()方法转化为json对象

var obj=eval("("+data+")");
//★eval()方法,将返回的不是标准json形式数据变成json对象形式【不推荐使用】

通过json插件返回后台数据

struts有json格式的,spring也有处理json的插件,以下的方式是使用alibaba的json插件。

public void reg(){
Map<String,Object> m = new HashMap<String,Object>();
try {
//▲注意点:如果add()的参数有100项,则应该直接传对象
userService.save(user);
m.put("success", true);
m.put("msg", "注册成功");
} catch (Exception e) {
m.put("success",false);
m.put("msg", e.getMessage());
}
super.writeJson(m);//调用父类的方法
}


注意:必须先通过以下方式引入alibaba的json插件

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.24</version>
</dependency>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  json ssh easyUI