我有一个活页夹,它将获得一连串的权限,必须将其转换为Collection。但是,当活页夹方法调用时,它无法将String数组转换为collection。

我的控制器:

@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;


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

最佳答案

您的编辑器似乎缺乏将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();
  }

}


将某种映射添加到查找许可权对象中,而不是一个一个地从数据库中获取它们,可能是一个好主意。构造函数中的内容如下:

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


然后使用setAsText()方法从该映射中检索对象:

res.add(map.get(v.trim());


希望能有所帮助。

08-25 06:16