StringMVC在方法返回值类型前面定义@ResponseBody注解,可以直接返回字符串,单个对象,一堆对象(list),有些时候我们返回这些同时,还需要返回一个是否错误代码等其他内容,此时我们可以定义一个工具类
例如:
public class JsonView {
//错误代码 0-成功
private Integer errcode = 0;
// 消息
private String message;
// 数据
private Object data;
public JsonView(Integer errcode, String message) {
this.errcode = errcode;
this.message = message;
}
public JsonView(Integer errcode) {
this.errcode = errcode;
}
public JsonView() {
}
public Integer getErrcode() {
return errcode;
}
public void setErrcode(Integer errcode) {
this.errcode = errcode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public String toString(){
return JSONObject.fromObject(this).toString();
}
public String toIso8859String() throws UnsupportedEncodingException{
return new String(this.toString().getBytes(), "ISO-8859-1");
}
}
下面是自定义实体类的用法
1、返回一个自定义的实体类
在controller类方法中,
//通过身份证号或姓名搜索学员信息
@RequestMapping(value="/appliInformationSearcher")
public @ResponseBody String appliInformationSearcher(int rows,int page, String name,String value, int termid){
Pagination apply = null;
try {
//URLDecoder.decode(name , "utf-8")前台传上来的汉字参数是乱码,转化字符串的,js中也要转化
apply = service.appliInformationSearcher(rows,page,URLDecoder.decode(name , "utf-8"), URLDecoder.decode(value , "utf-8"), termid);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonView jv=new JsonView();
jv.setData(apply);
return jv.toString();
}
js中用ajax请求时,data.data即是从后台传过来的集合apply,
$.post("appliInformationSelect1.html",//查询报名人员现场签到情况
{ id: rowData.id },
function(data){
var data1=data.data;
},'json');
注意:post中必须定义‘json’,否则接收不到数据
2、返回一个String字符串
Controller类中的方法,返回一个字符串
@RequestMapping(value="appliInformationsignin")
@ResponseBody
public String appliInformationsignin(SiteSign site){
String fhz=service.appliInformationsignin(site);
return fhz;
}
js中post方法请求
$.post("appliInformationsignin.html",//查询报名人员现场签到情况
{ userid:userid,termid:termid,signintime:rowData.intime,tsid:rowData.tsid},
function(data){
alert("ssssss");
});
注意:此时post方法不能定义‘json’,否则alert(),没有反应,接收不到数据