PDA

View Full Version : Exclude form bindings on fields depending on the called Controller-method



mikrobi
Apr 29th, 2010, 02:22 PM
Hey!

I've the following (simplified) problem: I've an user entity with name, email and password fields.

In my controller I've got two methods: one for registering a new user and one for updating a user:



@RequestMapping(value = "/user", method = RequestMethod.POST)
public String create(@Valid User user, BindingResult result,
ModelMap modelMap) {
//registration...
}

@RequestMapping(value = "/user", method = RequestMethod.PUT)
public String create(@Valid User user, BindingResult result,
ModelMap modelMap) {
//update...
}


I don't want a user to be able to change his name after registration.

I simply removed the <form:input path="name"> tag in the update.jsp but then the user's name was set to "" after updating.

Then I searched the Spring docs and found @InitBinder:



@InitBinder
public void initBinder(WebDataBinder binder, WebRequest request) {
binder.setAllowedFields("email", "password");
}


But initBinder will be called on every request (both update and registration). On registration I additionally want to allow the "name" field.

How can this be done without writing a separate controller?

mikrobi
Apr 29th, 2010, 04:03 PM
OK, I found a solution for my problem. Maybe this is useful for people having the same problem. Or maybe there's even a better way to solve this issue?

1. Set the SessionAttributes Annoatation to the controller to keep the values of excluded fields (@SessionAttributes("nameOfFormbackingObject").

2. Get the http method from the servletRequest to decide which fields should be blocked:



@SessionAttributes("user")
public class UserProfileController {

@InitBinder
public void initBinder(WebDataBinder binder, HttpServletRequest request) {
String httpMethod = request.getMethod();
if ("POST".equals(httpMethod)) {
// registration
binder.setAllowedFields("name", "email", "password");
} else if ("PUT".equals(httpMethod)) {
// update
binder.setAllowedFields("email", "password");
}

}

@RequestMapping(value = "/user", method = RequestMethod.POST)
public String create(@Valid User user, BindingResult result,
ModelMap modelMap) {
//registration...
}

@RequestMapping(value = "/user", method = RequestMethod.PUT)
public String create(@Valid User user, BindingResult result,
ModelMap modelMap) {
//update...
}

}