Spring MVC, one controller for "add" and "update" when using setDisallowedFields?

So, I have a simple form, thanks to which I can either “add” a new thing or “update” an existing Thing.

I would like to have one controller that can handle both add and update. From the very beginning, this seems simple enough until I consider the problem of using setDisallowedFields in my InitBinder so that the id field is not resolved when adding a new Thing.

I currently have two controllers with what may be identical code except the InitBinder method.

Any suggestions or tips? (I am open to the argument that I should also support two controllers, if you can give me good reasons)

+3
source share
3 answers

Actually, you should prohibit the "id" field both when adding and in updating. Otherwise, the attacker can change the value of the request parameter "id" of the update request and thereby update another record to the one shown by the form (if there is no ACL or other security at the domain level).

, "id" , null, , (, , , , ). , ( , ) , -. @SessionAttributes , ( ):

@SessionAttributes("thing") // the name of your domain object in the model
public class ThingController {

    public void setDisallowedFields(WebDataBinder binder) {
        binder.setDisallowedFields("id", "someOtherUneditableField");
    }

    // request handling methods go here as before
}

, . @SessionAttributes .

+3

initBinder HttpServletRequest:

protected void initBinder(HttpServletRequest request, 
    ServletRequestDataBinder binder)

, , initBinder() , , setDisallowedFields?

( , , ...)

+2

The way I do this with a single controller is to have a boolean in my command object indicating whether this is a new object or not. In onSubmit, I can check the boolean to see if I need to perform the add or update action.

+1
source

Source: https://habr.com/ru/post/1707707/


All Articles