方法一: 1、定义dojo form form id="CompanyForm" data-dojo-type="dijit/form/Form" onsubmit="return this.validate();" form中的元素必须有name属性,例如 input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="req
方法一:
1、定义dojo form
<form id="CompanyForm" data-dojo-type="dijit/form/Form" onsubmit="return this.validate();">
form中的元素必须有name属性,例如
<input data-dojo-type="dijit/form/ValidationTextBox" data-dojo-props="required : true" name="companyName" maxlength="20"/>
2、表单转为json,提交
function submit(){ var url = "/dojo/rest/echo/modCompany"; require(["dojo/request/xhr", "dojo/dom-form"], function(xhr, domForm){ xhr.post( url, { headers:{ 'Content-Type': 'application/json; charset=UTF-8' }, handleAs: "json", data: domForm.toJson("CompanyForm") }); }); }3、json值绑定到vo类,前提是json中的字段名称和vo类中的成员变量名称一一对应
例如:
json:{"companyName":"正一味","phone":"","addr":"","companyType":"zh"}
vo类:
public class Company{ private String companyName; private String phone; private String addr; private String companyType; 。。。。。。
需要用到的jar:
jackson-core-asl-1.8.5.jar
jackson-mapper-asl-1.8.5.jar
import org.codehaus.jackson.JsonParseException; import org.codehaus.jackson.map.JsonMappingException; import org.codehaus.jackson.map.ObjectMapper; 。。。。。。 @POST @Path("/modCompany") @Produces("application/json") public Company modCompany(@Context HttpServletRequest request) throws JsonParseException, JsonMappingException, IOException{ String json = (String)request.getParameterNames().nextElement(); ObjectMapper mapper = new ObjectMapper(); Company c = mapper.readValue(json, Company.class); }
这样,就把json中的值赋值给了vo类,省去了手工解析、赋值的麻烦
方法二:
比前述更加简便:其余不变,直接把vo类放到rest接口参数里面,Resteasy会自动绑定
@POST @Path("/modCompany") @Produces("application/json") @Consumes(MediaType.APPLICATION_JSON) public Company modCompany(Company c){。。。。。。}
方法三:
如果表单不转换为json,也能绑定
首先,dojo代码改为
function submit(){ require(["dojo/request/xhr", "dojo/dom-form"], function(xhr, domForm){ xhr.post("/dojo/rest/echo/modCompany", { headers:{ 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' }, //header有所变化 handleAs: "json", data: domForm.toObject("CompanyForm") //这里变为toObject }) }); }其次,vo类调整
public class Company{ @FormParam("companyName") //加上@FormParam private String companyName; private String phone; private String addr; private String companyType; 省略getter/setter }最后,rest接口调整
@POST @Path("/modCompany") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) @Produces("application/json") public Company modCompany(@Form Company c) //增加@Form
OK,到此为止,也同样实现了数据绑定
可见,方法二最为简洁
如果我们只想获取页面一部分数据,例如只取名为param的checkbox数组的值,则可以这样做:
首先,页面还是用domForm.toObject("CompanyForm")转换为对象,此时不能转换为json,headers参数可以不带
然后,后台方法使用@FormParam指明获取param的参数值
@POST @Path("/setSource") @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public void setSource(@FormParam("param") String[] param)