2016-03-24 14 views
0

私は、残りのコントローラが上に座ってspringbootアプリケーションがあります。そのようなJSONで/testを介してコントローラとが通過するユーザアクセス:Spring Controller Validate Request

{"ssn":""} 

{"ssn":"123456789"} 

は、私は、少なくともそのようで渡される空のSSNはありませんを確認することにより、入力を検証します

だからここに私のコントローラです:

@RequestMapping(
      value = "/test", 
      method = RequestMethod.POST, 
      consumes = "application/json", 
      produces = "application/json") 
@ResponseBody 
public JsonNode getStuff(@RequestHeader HttpHeaders header, 
           @RequestBody String payload, 
           BindingResult bindingResult) { 
    validator.validate(payload, bindingResult); 
    if(bindingResult.hasErrors()) { 
     throw new InvalidRequestException("The request is incorrect", bindingResult); 
    } 
    /* doing other stuff */ 
} 

そして、ここに私のバリデータです:

@Component 
public class RequestValidator implements Validator { 
    @Override 
    public boolean supports(Class<?> clazz) { 
     return false; 
    } 

    @Override 
    public void validate(Object target, Errors errors) { 
     ObjectMapper mapper = new ObjectMapper(); 
     JsonNode ssn = null; 
     try { 
      ssn = mapper.readTree((String) target); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     if(ssn.path("ssn").isMissingNode() || ssn.path("ssn").asText().isEmpty()) { 
      errors.rejectValue("ssn", "Missing ssn", new Object[]{"'ssn'"}, "Must provide a valid ssn."); 
     } 
    } 
} 

私は郵便配達でこれをテストしようと、私はこのエラーを取得しておいてください。

HTTP Status 500 - Invalid property 'ssn' of bean class [java.lang.String]: Bean property 'ssn' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter? 

まさにここでの問題は何?ゲッターやセッターとの関係で何が話しているのか分かりません。

編集1:デフォルト春ブーツが要求した

{"ssn":""} 
+0

何らかの理由で「サポート」がfalseを返す。 – Sanj

+0

@サニャ・オア・ノー、そうではありません。他の実装を提供することを迷惑に掛けずに済ませました。 – Richard

+0

ペイロードの価値は何ですか?コントローラのSystem.out.println(ペイロード)。 – Sanj

答えて

1

としてペイロードの値は、JSONパーサーを設定するので、あなたは、コントローラに渡す任意のJSONを解析できます。 Springは、リクエスト値をバインドするために 'ssn'というプロパティを持つオブジェクトが必要です。

これは、あなたがこのようなモデルオブジェクトを作成する必要があることを意味します

public class Data { 
    String ssn; 

} 

をそして、このようなあなたのリクエストボディをバインドするためにそれを使用する:

@RequestMapping(
     value = "/test", 
     method = RequestMethod.POST, 
     consumes = "application/json", 
     produces = "application/json") 
@ResponseBody 
public JsonNode getStuff(@RequestHeader HttpHeaders header, 
           @RequestBody Data payload, 
           BindingResult bindingResult) { 
    validator.validate(payload, bindingResult); 
    if(bindingResult.hasErrors()) { 
     throw new InvalidRequestException("The request is incorrect", bindingResult); 
    } 
    /* doing other stuff */ 
} 

あなたはまた、使用するために、あなたのバリデータを適応させる必要がありますこの新しいDataオブジェクト。

関連する問題