如何将String []绑定到POJO的集合?

时间:2014-03-24 18:57:24

标签: java jsp spring-mvc

我有一个绑定器,它获取一串权限,必须将其转换为Collection。但是当调用binder方法时,它无法将String数组转换为集合。

我的控制器:

@Controller
@RequestMapping("/profile")
public class ProfileController {
    @Autowired
    @Qualifier("mvcUserService")
    UserService userService;

    @RequestMapping(value = "/edit", method = RequestMethod.GET)
    public ModelAndView editForm(Principal principal) {
        User user = userService.getUser(principal.getName());
        ModelAndView mav = new ModelAndView("user/profile");
        return mav.addObject("user", user);
    }

    @RequestMapping(value = "/edit", method = RequestMethod.PUT)
    public ModelAndView edit(@ModelAttribute("user") User user, BindingResult result) {
        // some action with User object
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        binder.registerCustomEditor(Permission.class, new PropertyEditorSupport() {
            @Override
            public void setAsText(String name) throws IllegalArgumentException {
                Permission permission = userService.getPermission(name);
                setValue(permission);
            }
        });

JSP:

<form:form action="/profile/edit" method="PUT" modelAttribute="user">
<input type="hidden" name="_method" value="PUT"/>

// setting up fields

<form:hidden path="id"/>
<form:hidden path="permissions"/>
</form:form>

许可类:

public class Permission implements Serializable {
    private Integer id;
    private String name;

我的用户类:

public class User implements Serializable {

    // some fields

    private Collection<Permission> permissions;

我需要实现正确的绑定。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您的编辑器似乎缺乏将CSV列表转换为对象列表的逻辑。下面是PermissionListEditor的代码,它将逗号分隔的字符串列表转换为List集合:

public class PermissionListEditor extends PropertyEditorSupport {

  @Override
  public void setAsText(String text) throws IllegalArgumentException {
    List<Permission> res = new ArrayList();
    for (String v: text.split(",")) {
      if (v.trim().length() > 0)
        res.add(userService.getPermission(v.trim()));
    }
    setValue(res);
  }

  @Override
  public String getAsText() {
    StringBuilder val = new StringBuilder();
    for (Permission p: (List<Permission>) getValue()) {
      if (val.length() > 0) val.append(", ");
      val.append(p.getName());
    }
    return val.toString();
  }

}

添加某种映射来查找Permission对象可能是一个好主意,而不是逐个从数据库中提取它们。在构造函数中有类似的东西:

Map<String, Permission> map = new HashMap()<>;
for (Permission p: userService.listPermissions();
  map.add(p.getName(), p);

然后只需从setAsText()方法中检索该地图中的对象:

res.add(map.get(v.trim());
希望有所帮助。