Reputation: 86747
I have a Servlet with a parameter bean. The bean has some fields that should no be able to override by the users get-query.
How can I achieve it?
None of the following worked:
@JsonIgnore
@XmlTransient
@JsonIgnoreProperties
private String somefield;
Run:
localhost:8080/myservlet?somefield=xxx
This will alter the property directly. How can I tell spring to skip that property?
Or even better: let spring reject the request as the user tried to change an unallowed property?
Upvotes: 1
Views: 1342
Reputation: 3561
If by servlet you mean controller you can configure binder to ignore some properties of model class:
@RestController
public class MyServlet {
@InitBinder
private void initBinder(WebDataBinder binder) {
binder.setDisallowedFields("somefield");
}
@GetMapping("/myservlet")
public String myservlet(Model model) {
return model.toString();
}
}
Model:
public class Model {
private String somefield;
private String property2;
//getters and setters
}
Another way is to remove the ignored property setter from model class at all. In that case spring will not be able to set the value.
If by servlet you mean servlet then just wrap the request excluding ignoring properties from getParameterMap()
call.
Update
If you want to force spring to reject entire request when inappropriate property is set then you can register a custom property editor for this very property and throw an exception within setValue method. Like this:
@InitBinder
private void initBinder(WebDataBinder binder) {
// binder.setDisallowedFields("property1");
binder.registerCustomEditor(String.class, "somefield", new PropertyEditorSupport() {
@Override
public void setValue(Object value) {
throw new IllegalStateException();
}
});
}
Another way is to throw an exception within property setter in Model
class. Spring then catch it, wrap into its own org.springframework.validation.BindException
and return with 400 bad request
.
Upvotes: 3