J2EE中使用json数据流程是什么呢?
1 jsp传值至action
2 action中处理jsp传来的值,一番处理之后,处理成json格式的值
3 传回jsp。jsp中可以通过拿到的处理后的数据。通过键值对的形式拿到值。
JSP
$('select[name=classes').change(function(){
var classNum= $('select[name=classes option:selected').val();
$.getJSON(
"stu/stu_toshowStu",
{classNum:classNum},
function(json,status)
{
$.each(json,function(i){
$('#stuDiv').append("<div>学生学号:"+json[i].num+"</div>" );
}
);
});
Action
private String classNum;
.........................................
public String toshowStu()
{
List<Student> lstStu = stuService.getStuByClassNum(classNum);
this.outputJson(lstStu );
return null;
}
outputJson
protected final void outputJson(Object obj)
{
String outStr = "";
if(obj instanceof String)
outStr = (String)obj;
else
outStr = getJson(obj);
try
{
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.getWriter().print(outStr);
}
catch(IOException e)
{
logger.error(e.getMessage(), e);
e.printStackTrace();
}
}
protected final String getJson(Object obj)
{
JsonConfig cfg = jsonCfg();
return JSONArray.fromObject(obj, cfg).toString();
}
private JsonConfig jsonCfg()
{
JsonConfig cfg = new JsonConfig();
cfg.registerJsonValueProcessor(java/util/Date, new JsonValueProcessorImpl());
return cfg;
}
student本身有num这个字段,将数据对象处理成json格式的数据,其中有[{"num":"111","name":"222","address":"江苏"}]等等。
当然,我们肯定要导包啦。详见:http://blog.csdn.net/woshixuye/article/details/7244318