java - 关闭 Spring MVC 数据绑定(bind)器

标签 java spring spring-mvc

关于 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/

相关文章:

java - 如何将图像从Android客户端传输到Java服务器

java - 如何在spring项目中读取属性文件?

java - 事务的传播行为

spring - 蒙戈 : repositories no longer works

spring-mvc - thymeleaf + polymer

java - 错误 ="invalid_grant", error_description ="Bad credentials"在 Spring oauth2

java - 如何使用Web App和Android App访问SQL数据库

java - Cucumber 中可以同时使用 DataTable 和 Parameter 吗?

java - 是否可以使用 Spring MVC 提取映射并从 URL 参数中分离变量?

java - 如何从 Java 类调用 spring 组件