Spring MVC POJO Bind解释

时间:2010-04-27 19:07:16

标签: spring-mvc

我试图理解对象的绑定如何在spring mvc中工作。我有一个Controller设置如下,并希望将freemarker模板绑定到accessRequestBean。在模板中我有'< @ spring.bind'command.accessRequestBean“/>'但这会导致错误......如何将表单绑定到POJO?

@Controller
@PreAuthorize("isAuthenticated()")
@RequestMapping("/access")
public class RemoteVendorAccessController {
    private Logger logger = Logger.getLogger(this.getClass().getName());

    @Autowired
    private AdDao adDao;

    @Autowired
    private CadaDao cadaDao;

    @Autowired
    private UserAccessCache userAccessCache;

    private AccessRequestBean accessRequestBean;

    @RequestMapping(method = RequestMethod.GET)
    public String requestAccess(ModelMap map){
        String username = SecurityContextHolder.getContext().getAuthentication().getName();
        map.addAttribute("title", "Remote Vendor Access Request Form");

        try {
            AdUser user = adDao.getUserFromNt(username);
            map.addAttribute("user", user);
        } catch (UserDoesNotExistException e) {
            String error = "Could not get user information from AD";
            map.addAttribute("error", error);
            logger.error(error + "[" + username + "]", e);
        }

        // Get users manager
        AdUser manager = null;
        try {
            manager = adDao.getManagerFromNt(username);
            map.addAttribute("manager", manager);           
        } catch (Exception e) {
            String error = "Could not get manager information from AD";
            map.addAttribute("error", error);
            logger.error(error + "[" + username + "]", e);
        }

        return("access");
    }

    @RequestMapping(method = RequestMethod.POST)
    public String processRequest(ModelMap map){
            // Want to validate POJO bean here          
        return(null);
    }

    public AccessRequestBean getAccessRequestBean() {
        return accessRequestBean;
    }

    public void setAccessRequestBean(AccessRequestBean accessRequestBean) {
        this.accessRequestBean = accessRequestBean;
    }


}

1 个答案:

答案 0 :(得分:2)

根据Spring Documentation,控制器通过在方法参数上使用@ModelAttribute注释来获取对包含在表单中输入的数据的对象的引用。参数类型将是您的POJO类,它对应于用于在编辑模板上构造表单的对象。即

@RequestMapping(method = RequestMethod.POST)
public String processRequest(
         @ModelAttribute POJO pojo,
         BindingResult result,
         ModelMap map){
    new POJOValidator().validate(pojo, result);
    if (result.hasErrors()) {
        return "pojoForm";
    }
    .
    .
    .  
    return(null);
}