[英]Spring Boot Pojo of Pojo validation not working
I have two Pojo in my spring boot application我的 spring 启动应用程序中有两个 Pojo
Pojo 1: FeedData Pojo 1:FeedData
Code(i have the get and set, just didn't show it here):代码(我有get和set,只是这里没有显示):
package com.cms.tb.model;
import java.io.Serializable;
import javax.validation.constraints.NotBlank;
import com.fasterxml.jackson.annotation.JsonProperty;
public class FeedData implements Serializable{
@JsonProperty("feed_id")
private int feedId;
@JsonProperty("feed_category_id")
private int feedCategoryId;
@JsonProperty("feed_data_json")
private FeedDataJson feedDataJson;
@JsonProperty("user_profile")
private UserProfile userProfile;
}
..in the above pojo, there is another Pojo called FeedDataJson which has validations. ..在上面的 pojo 中,还有另一个名为 FeedDataJson 的 Pojo 具有验证功能。
Code 2: FeedDataJson Pojo代码 2:FeedDataJson Pojo
package com.cms.tb.model;
import java.util.List;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import com.fasterxml.jackson.annotation.JsonProperty;
public class FeedDataJson {
@NotBlank(message = "feed_title is Mandatory")
@Size(min = 4, max = 25, message
= "feed_title must be between 4 and 25 characters")
@JsonProperty("feed_title")
private String feedTitle;
@NotBlank(message = "feed_body is Mandatory")
@Size(min = 4, max = 2000, message
= "feed_body must be between 10 and 2000 characters")
@JsonProperty("feed_body")
private String feedBody;
@JsonProperty("feed_meta_tags")
private List<String> feedMetaTags;
}
whenever i send a request via POSTMAN, there validations are not happening in FeedDataJson Pojo.每当我通过 POSTMAN 发送请求时,FeedDataJson Pojo 中都不会发生验证。
sample request data:样品请求数据:
{
"feed_data_json":{
"feed_title":"",
"feed_body":"LOL",
"feed_meta_tags":["m1"]
},
"feed_category_id":1,
"user_profile":{
"user_id":1
}
}
This should throw an Validation Error, because feed_title is empty,right?这应该会引发验证错误,因为 feed_title 是空的,对吧?
my Controller code:我的 Controller 代码:
@PostMapping(path="/v1/createfeed")
public ResponseEntity<String> createFeedController(@Valid @RequestBody FeedData requestData)
throws TBFeedException, TBFeedDBException, JsonProcessingException {
// Create ObjectMapper
ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String feedDataJson = mapper.writeValueAsString(requestData.getFeedDataJson());
FeedData newFeedInfo = ITBFeedDAO.createFeed(requestData,feedDataJson);
newFeedInfo.setFeedDataJson(requestData.getFeedDataJson());
JsonNode dataNode = mapper.valueToTree(newFeedInfo);
return new ResponseEntity<String>(generateResponse(dataNode), setHeaders(), HttpStatus.OK);
}
Use @Valid on feedDataJson
propertry in FeedData
class.在
feedDataJson
class 中的FeedData
属性上使用 @Valid。
@Valid
private FeedDataJson feedDataJson;
For nested property, you need to use @Valid also.对于嵌套属性,您还需要使用 @Valid。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.