2015-10-06 46 views
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,因爲我選中了)?

+0

啓用調試日誌。 Spring在那裏打印異常消息。 –

+0

所有可序列化類都需要一個無參數構造函數。這是java的基本規則,而不是Spring本身的限制。 (傑克遜容忍你不會標記不可承受的序列化類)) – Affe

回答

1

As @Sotitios表示您可以啓用調試日誌,您可以通過向資源文件夾添加logback.xml(也可以是常規)來執行此操作。這裏是我的

<configuration> 
    <appender name="FILE" 
     class="ch.qos.logback.core.rolling.RollingFileAppender"> 
     <File>logFile.log</File> 
     <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> 
      <FileNamePattern>logFile.%d{yyyy-MM-dd}.log</FileNamePattern> 
      <maxHistory>5</maxHistory> 
     </rollingPolicy> 

     <layout class="ch.qos.logback.classic.PatternLayout"> 
      <Pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{35} - 
       %msg%n</Pattern> 
     </layout> 
    </appender> 

    <root level="DEBUG"> 
     <appender-ref ref="FILE" /> 
    </root> 

</configuration> 

關於你無參數的構造函數問題,你可以創建自己的構造函數,並迫使傑克遜使用它,我相信這是一個很好的做法,因爲你有mutablity更多的控制

@JsonCreator 
    public UserDto(
      @JsonProperty("id") Long id, 
      @JsonProperty("firstName") String firstName, 
      @JsonProperty("lastName") String lastName, 
      @JsonProperty("emailAddress") String emailAddress, 
      @JsonProperty("active") boolean active, 
      @JsonProperty("position") String position, 
      @JsonProperty("pendingDays") Integer pendingDays, 
      @JsonProperty("taxUid") String taxUid, 
      @JsonProperty("userName") String userName, 
      @JsonProperty("approver") boolean approver, 
      @JsonProperty("startWorkingDate") Date startWorkingDate, 
      @JsonProperty("birthDate") Date birthDate){ 

     this.id = id; 
     this.firstName = firstName; 
     this.lastName = lastName; 
     this.taxUid = taxUid; 
     this.userName = userName; 
     this.emailAddress = emailAddress; 
     this.pendingDays = pendingDays; 
     this.position = position; 
     this.active = active; 
     //this.resourceUrl = resourceUrl; 
     this.isApprover = approver; 
     this.birthDate = birthDate; 
     this.startWorkingDate = startWorkingDate; 

    } 

希望這有助於

相關問題