0
我只是用彈簧啓動打,只是想與創建一個控制器method = RequestMethod.POST
爲什麼@RequestBody不需要arg構造函數?
我的控制器:
@RequestMapping(value = "/user/signup",
method = RequestMethod.POST)
private String signUpNewUser(@Valid @RequestBody SignInUserForm userForm){
// validation + logic
}
SignUpUserForm類:
@Getter
@NoArgsConstructor
@AllArgsConstructor
public class SignInUserForm {
@NotEmpty
@Email
private String email;
@NotEmpty
@Size(min = 8, max = 24)
private String password;
@NotEmpty
@Size(min = 8, max = 24)
private String repeatedPassword;
}
,最後我的測試:
@Test
public void shouldCallPostMethod() throws Exception {
SignInUserForm signInUserForm = new SignInUserForm("[email protected]", "aaaaaaaa", "aaaaaaaa");
String json = new Gson().toJson(signInUserForm);
mockMvc.perform(
MockMvcRequestBuilders.post("/user/signup")
.contentType(MediaType.APPLICATION_JSON_VALUE)
.content(json))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isCreated());
}
as far作爲SignUpControllerForm包含無參數的構造函數,一切工作正常,但一旦缺少這就是我從MockMvcResultHandlers.print()
得到:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /user/signup
Parameters = {}
Headers = {Content-Type=[application/json]}
Handler:
Type = org.bitbucket.akfaz.gui.controller.SignUpController
Method = private java.lang.String org.bitbucket.akfaz.gui.controller.SignUpController.signUpNewUser(org.bitbucket.akfaz.gui.model.SignInUserForm)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.http.converter.HttpMessageNotReadableException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
我想表達的是,異常HttpMessageNotReadableException
是不是有足夠的描述。不應該有任何與@RequestBody相關的異常嗎?這將節省很多時間。
Spring如何將JSON轉換爲無參數構造函數的java對象(它不使用getters,因爲我選中了)?
啓用調試日誌。 Spring在那裏打印異常消息。 –
所有可序列化類都需要一個無參數構造函數。這是java的基本規則,而不是Spring本身的限制。 (傑克遜容忍你不會標記不可承受的序列化類)) – Affe