Springmvc 前台传递参数到后台需要数据绑定

我们知道,当提交表单时,controller会把表单元素注入到command类里,但是系统注入的只能是基本类型,如int,char,String。但当我们在command类里需要复杂类型,如Integer,date,或自己定义的类时,controller就不会那么聪明了。这时,就需要我们帮助他们了。

后台controller:

@Controller
@RequestMapping(value = { "/projects/project" })
public class ProjectsController {
@Autowired
ProjectsService projectService;
@Autowired
UniskUserService userService;
@Autowired(required = false)
UserAndUserGroupService ugroupService;
public static final String path = "sys/modules/project/";
private static final Logger logger = LoggerFactory
.getLogger(ProjectsController.class);
/*
* 日期绑定转化
*/
@InitBinder
public void initBinder(WebDataBinder binder) throws Exception {
//Projects projects
binder.registerCustomEditor(Date.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
setValue(sdf.parse(text));
} catch (ParseException e) {
// TODO Auto-generated catch block
 e.printStackTrace();
}
}
});
}
//controller

/*
* 修改子项目实现
*/
@ResponseBody
@RequestMapping(value = "editSub", method = RequestMethod.POST)
public String editSub(HttpServletRequest request,HttpServletResponse response,@ModelAttribute("user") UniskUser user,@ModelAttribute("projects") Projects project, ModelMap map) throws UniskException {
projectService.update(project);
Map<String, String> result = new HashMap<String, String>();
result.put("resultCode", "0");
result.put("msg", "操作成功!");
System.out.println("edit");
return JsonUtil.toJson(result);
}

} 

前台表单:

   
   
   
   
<div class="control-group"> <label class="control-label">项目发布时间:</label> <div class="controls"> <input type="text" readonly id="starttime" name="starttime" maxlength="50" class="required times" placeholder="<fmt:formatDate value='${project.starttime }' pattern='yyyy-MM-dd'/>" /> </div> </div> <div class="control-group"> <label class="control-label">项目众筹时间:</label> <div class="controls"> <input type="text" readonly id="crowdtime" name="crowdtime" maxlength="50" class="required times" placeholder="<fmt:formatDate value='${project.crowdtime }' pattern='yyyy-MM-dd'/>" /> </div> </div> <div class="control-group"> <label class="control-label">项目验收时间:</label> <div class="controls"> <input type="text" readonly id="examinetime" name="examinetime" maxlength="50" class="required times" placeholder="<fmt:formatDate value='${project.examinetime }' pattern='yyyy-MM-dd'/>" /> </div> </div> <div class="control-group"> <label class="control-label">项目结束时间:</label> <div class="controls"> <input type="text" readonly id="endtime" name="endtime" maxlength="50" class="required times" placeholder="<fmt:formatDate value='${project.endtime }' pattern='yyyy-MM-dd'/>" /> </div> </div>

  getAsText和setAsText是要从新定义的。其中getAsText方法在get方法请求时会调用,而setAsText方法在post方法请求时会调用。

你可能感兴趣的:(Springmvc 前台传递参数到后台需要数据绑定)