简体   繁体   中英

Spring MVC 3 - Binding parameters to backing object

I am trying to setup an edit form for my User object. I have automatic binding from the form to the user object working fine.

I'm wondering how do I prevent malicious users from binding to fields of my User object that I don't want them to?

For example, my user object has userName , and it also has points . When they click edit user, I want them to be able to change the userName , but not the points . A malicious user could just send an extra points=429429 as a hidden field in the form by editing the HTML, and this would automatically be bound to the backing object by Spring.

I would suggest separating your front-end code from the logic for what will be saved in the database. The form backing object is just meant to be a simple object that captures want the user has done in the view... it shouldn't be used to save directly to the database. I would have a Service layer handle the decision on whether or not to update certain fields... the controller should just receive the input and pass it along. This way, the service can decide what fields should be updated.

public void updateUser(long userId, User updatedUser) {
    User currentUser = dao.getCurrentUserById(userId);
    currentUser.userName = updatedUser.username;
    //...... update anyother fields....
    dao.SaveUser(currentUser);
}

or you could define the method in a way that the caller knows what will be updated:

public void updateUser(long userId, String updatedUsername);

I would also argue that this is a lot easier to unit test if this logic is in the Service Layer.

Hope this helps

Add this to your controller:

@InitBinder
protected void initBinder(WebDataBinder binder) {
 binder.setAllowedFields("field1", "field2");
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM