2017-09-14 127 views
1

我與春天有引導休息實現的控制器:如何驗證Spring Boot Rest響應?

@RestController 
@RequestMapping("/example") 
public class ExampleController { 

    @Autowired 
    private ExampleService exampleService; 

    @GetMapping("/{id}") 
    public ExampleResponse getExample(@NotNull @PathVariable("id") String id) { 
     return exampleService.getExample(id); 
    } 
} 

和響應DTO:

public class ExampleResponse { 

    @NotNull 
    private String id; 

    @NotNull 
    private String otherStuff; 

    // setters and getters 
} 

響應體未通過驗證。我已用@Valid對其進行了註釋,但null值仍然通過。請求驗證很有效。

如何驗證響應主體?

+0

ü可以共享業務邏輯?你如何返回exampleService? – Balasubramanian

+2

這是我第一次聽說「響應驗證」,通常你只是驗證請求。你確定有這樣的事情嗎? –

+0

我需要檢查是否填寫了所有必需的值。我可能會使用「@Autowired 驗證程序驗證程序」,或者在服務中明確檢查它們,但是如果有其他方式執行,則有興趣。 – Justas

回答

1

採取的應對驗證:

@Aspect 
@Component 
public class ControllerResponseValidator { 

    Logger logger = Logger.getLogger(ControllerResponseValidator.class); 

    @Autowired 
    private Validator validator; 

    @AfterReturning(pointcut = "execution(* com.example.controller.*.*(..))", returning = "result") 
    public void validateResponse(JoinPoint joinPoint, Object result) { 
     validateResponse(result); 
    } 

    private void validateResponse(Object object) { 

     Set<ConstraintViolation<Object>> validationResults = validator.validate(object); 

     if (validationResults.size() > 0) { 

      StringBuffer sb = new StringBuffer(); 

      for (ConstraintViolation<Object> error : validationResults) { 
       sb.append(error.getPropertyPath()).append(" - ").append(error.getMessage()).append("\n"); 
      } 

      String msg = sb.toString(); 
      logger.error(msg); 
      throw new RestException(HttpStatus.INTERNAL_SERVER_ERROR, msg); 
     } 
    } 
} 
0

不應該將它註釋爲下面的代碼片段嗎?

public @ResponseBody ExampleResponse getExample(@NotNull @PathVariable("id") String id) { 
     return exampleService.getExample(id); 
    } 
+0

它不起作用。 – Justas

0

您可以添加 「@Validated @ResponseBody」 註釋

public @Validated @ResponseBody getExample(@NotNull @PathVariable("id") String id) { 
+0

它不起作用。 – Justas

0

你期望發生的?我看到你應該考慮的一些事情。

  1. 如果一個對象必須真的不具有的null值字段,您應該驗證此當對象被保存到存儲庫(即以往那種你喜歡的)。然後,如果你的服務返回一些東西,你知道它已經是有效的,如果它什麼都不返回;您可以爲客戶端返回適當的狀態碼和消息(4xx/5xx)。您也可以將特定的異常映射到特定類型的status code所以你可以從你的代碼拋出的異常,並讓他們被抓住,並在春季啓動由默認的異常處理程序處理

  2. 如果你的字段可以null ,但是你想在序列化中省略它們,你可以使用jackson annotations@JsonInclude(JsonInclude.Include.NON_NULL)只會序列化響應中的非空值。

相關問題