关于 stackoverflow 的第一篇文章...我开始尝试使用 SpringMVC,我试图找出将我的实体尽可能无状态地链接到 Web View 的最佳方法。
我发现的一种方法是在接收参数(来自请求)实体 ID 的方法上使用 @ModelAttribute,实体 ID 从服务/持久层找到它,然后返回它,以便将其插入到当前请求的模型。
此外,Spring MVC 绑定(bind)与我的实体字段匹配的任何传入参数并自动更新其值(通过 WebDataBinder)。
我的问题是关于最后一个行为。我发现在客户端发布某些数据时更新我的实体很有用。但我想在一个简单的 GET 请求(我认为它是只读的)上避免它。当前行为允许通过在此类请求的查询中添加参数来更新实体,这可能是一个安全问题。
我知道 dataBinder.setAllowedFields() 和其他东西,但我更喜欢一种方法来禁用任何类型的字段映射到任何 GET 请求。有什么办法吗?
谢谢!
已编辑:我添加了一个示例原型(prototype),以便更清楚地说明我在寻找什么......
@ModelAttribute Entity retrieveEntity(@RequestParam(required=true) Long id) {
// This is called before the request handler and before parameters are mapped to the entity
return entityRepository.get(id);
}
@RequestMapping(value="/modify", method=RequestMethod.POST)
public ModelAndView handleModifyRequest(@ModelAttribute Entity entity) {
// Here, I want my entity to reflect the parameters passed in the posted form (this works)
....
}
@RequestMapping(value="/read", method=RequestMethod.GET)
public ModelAndView handleReadRequest(@ModelAttribute Entity entity) {
// Here, I DON'T want my entity to reflect the parameters passed in the URL (which is what happens...)
....
}
最佳答案
最后,我决定采用类似的方法,因为似乎只有当请求处理程序方法采用 ModelAttribute 参数时才会发生参数映射
@ModelAttribute Entity retrieveEntity(@RequestParam(required=true) Long id) {
return entityRepository.get(id);
}
@RequestMapping(value="/modify", method=RequestMethod.POST)
public ModelAndView handleModifyRequest(@ModelAttribute Entity entity) {
// Here, the request parameters have been mapped to the entity
....
}
@RequestMapping(value="/read", method=RequestMethod.GET)
public ModelAndView handleReadRequest(ModelMap model) {
// This will avoid any parameter mapping to the entity
Entity entity = (Entity)model.get("entity");
....
}
欢迎任何更好的解决方案!谢谢
关于java - 关闭 Spring MVC 数据绑定(bind)器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12982237/