关闭Spring MVC数据绑定器

时间:2012-10-19 20:47:29

标签: java spring spring-mvc

关于stackoverflow的第一篇文章...我开始玩SpringMVC了,我试图弄清楚将我的实体链接到Web视图的最佳方法是尽可能无状态。

我发现的一种方法是在一个方法中使用@ModelAttribute,该方法在参数(来自请求)中接收实体ID,该实体ID从服务/持久层中找到它,并将其返回以便将其插入到当前请求的模型。

此外,Spring MVC绑定任何与我的实体字段匹配的传入参数,并自动更新其值(通过WebDataBinder)。

我的问题是关于这最后的行为。我发现当客户发布一些数据时,我的实体会更新很有用。但我想在一个简单的GET请求(我认为只读)上避免它。当前行为将允许通过在此类请求的查询中添加参数来更新实体,这可能是安全问题。

我知道dataBinder.setAllowedFields()和东西,但我更喜欢一种方法来禁用任何类型的字段映射任何GET请求。有没有办法做到这一点?

谢谢!

已编辑:我添加了一个示例原型,以便更清楚地了解我...

@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...)
    ....
}

1 个答案:

答案 0 :(得分:2)

最后,我决定使用类似的东西,因为看起来只有在请求处理程序方法采用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");
    ....
}

欢迎任何更好的解决方案!感谢