Data binding without using spring taglib

拈花ヽ惹草 提交于 2019-12-21 20:16:32

问题


My html is built without using the spring taglib and now I'd like to bind the parameters of the form to a object in my controller.

Currently my form looks like this

<form>
<input type="text" name="frAccUserMgmt.userName"/>
<input type="password" name="frAccUserMgmt.userPwd"/>
</form>

The relevant part of my object is

Class FrAccUserMgmt {
    private String userName;
    private Strint userPwd;
    // getter and setter
}

My controller is

@RequestMapping("login")
Public ModelAndView doLogin(FrAccUserMgmt frAccUserMgmt) {
    //code
}

How do I go about binding it. Currently the binding doesn't happen. I just get an empty object in my code.


回答1:


You could try including the BindingResult class in the method signature and then see if there are any binding errors:

@RequestMapping("login")
Public ModelAndView doLogin(FrAccUserMgmt frAccUserMgmt, BindingResult result) {
    if (result.hasErrors()) {
        logger.warn("BindingResult errors: " + result.toString());
    }
    //code
}

Remove the frAccUserMgmt part from the form field names. Spring will automatically find the command object to bind the request parameters based on the getters and setters defined in the command object.




回答2:


This can also be done by adding the @ModelAttribute for the parameter bean that should be populated with the request parameters.

As per spring docs

http://docs.spring.io/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-ann-modelattrib-method-args (16.3.3.8 Using @ModelAttribute on a method argument)

An @ModelAttribute on a method argument indicates the argument should be retrieved from the model. If not present in the model, the argument should be instantiated first and then added to the model. Once present in the model, the argument's fields should be populated from all request parameters that have matching names. This is known as data binding in Spring MVC, a very useful mechanism that saves you from having to parse each form field individually.



来源:https://stackoverflow.com/questions/11603619/data-binding-without-using-spring-taglib

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!