我想在表单上的另一个对象内发送一个列表。在这种情况下,它是具有角色列表的用户。在表单上,我有一个选择多个发送角色 ID 列表。我有一个带有 RoleFormatter 的自定义 FormatterRegistrar。这是我的代码:
我的模型:
@Entity
@Table(name = "USER")
@SequenceGenerator(name = "user_seq", sequenceName = "user_seq", initialValue = 1)
public class User implements Serializable {
@Id
@GeneratedValue(generator = "user_seq", strategy = GenerationType.SEQUENCE)
private Long id;
@NotEmpty
@Size(min = 1, max = 50)
@Column(name = "codigo", nullable = false)
private String codigo;
@Size(min = 3, max = 50)
@Column(name = "name")
private String name;
....
@NotNull
@NotEmpty
@ManyToMany
@JoinTable(name = "user_roles",
joinColumns = { @JoinColumn(name = "user_id", referencedColumnName = "id") },
inverseJoinColumns = { @JoinColumn(name = "role_id", referencedColumnName = "id") }
)
private Set<Role> roles = new HashSet<>();
//getters & setters
}
我的控制器:
@Controller
@SessionAttributes("user)
@RequestMapping(value = "/users")
public class UserController {
@PreAuthorize("hasAuthority('users.admin')")
@RequestMapping(value = "update", method = RequestMethod.POST)
public String save(@Valid @ModelAttribute User user, BindingResult result, SessionStatus status, RedirectAttributes ra,
HttpServletRequest request) {
//Save user
return "detail";
}
}
我的测试:
public class UserControllerTest {
@Mock
private UserService userService;
@InjectMocks
private UserController userController;
private MockMvc mockMvc;
@Before
public void setup() {
// Process mock annotations
MockitoAnnotations.initMocks(this);
// Setup Spring test in standalone mode
this.mockMvc = MockMvcBuilders.standaloneSetup(userController)
.setCustomArgumentResolvers(new PageableHandlerMethodArgumentResolver()).build();
}
@Test
public void testSave() throws Exception {
User user = new User();
// Without errors
this.mockMvc.perform(post("/users/update")
.param("id", "1")
.param("name", "Jonh")
.param("roles.id", "1", "2")
.sessionAttr("user", user))
.andExpect(view().name("detail"))
.andExpect(model().hasNoErrors()));
}
}
通过这个测试,我总是得到空角色。如何提交 id 列表?如何发送列表?