我有一个 POST 方法,用于发送“Item”。每个“Item”都包含作者的用户 ID。为了获取作者 ID,我使用:
从浏览器表单发送数据时为什么不会抛出
谢谢您。
更新:
(User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
但是在测试中,由于结果以下原因,它不能正常工作:
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.ClassCastException: org.springframework.security.core.userdetails.User cannot be cast to ru.pravvich.domain.User
POST 方法:@PostMapping("/get_all_items/add_item_page/add_item")
public String addItem(@RequestParam(value = "description") final String description) {
final User user = (User) SecurityContextHolder
.getContext()
.getAuthentication()
.getPrincipal();
final Item item = new Item();
item.setDescription(description);
item.setAuthorId(user.getId());
service.add(item);
return "redirect:/get_all_items";
}
And test:
@Test
@WithMockUser(username = "user", roles = "USER")
public void whenPostThenAdd() throws Exception {
Item item = new Item();
item.setDescription("test");
mvc.perform(
post("/get_all_items/add_item_page/add_item")
.param("description", "test")
).andExpect(
status().is3xxRedirection()
);
verify(itemService, times(1)).add(item);
}
从浏览器表单发送数据时为什么不会抛出
ClassCastException
?如何解决这个问题?谢谢您。
更新:
@Service
public class UserService implements UserDetailsService {
@Autowired
private UserRepository userRepo;
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
User user = userRepo.findByUsername(username);
if (user == null) user = new User();
return user;
}
}
@WithUserDetails
?https://docs.spring.io/spring-security/site/docs/current/reference/html/test-method.html#test-method-withuserdetails - Daniel C.