【发布时间】:2021-08-15 08:20:05
【问题描述】:
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Valid;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import lombok.extern.slf4j.Slf4j;
import com.example.demo.entity.Country;
import com.example.demo.repository.CountryRepository;
@Slf4j
@RestController
@RequestMapping("/countries")
public class CountryController {
@Autowired
private Country country;
@PostMapping
public Country addCountry(@RequestBody @Valid Country country){
log.info("Started");
// Create validator factory
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
// Validation is done against the annotations defined in country bean
Set<ConstraintViolation<Country>> violations = validator.validate(country);
List<String> errors = new ArrayList<String>();
// Accumulate all errors in an ArrayList of type String
for (ConstraintViolation<Country> violation : violations) {
errors.add(violation.getMessage());
}
// Throw exception so that the user of this web service receives appropriate error message
if (violations.size() > 0) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, errors.toString());
}
return country;
}
}
每当我发送发布请求时,我都会收到错误 java.lang.ClassNotFoundException: javax.validation.Validation。我试着用 git bash -> curl -i -H 'Content-Type: application/json' -X POST -s -d '{"code":"IN","nae":"India"}' http 写这个://localhost:8080/国家 我得到了错误
【问题讨论】:
标签: java spring-boot spring-mvc spring-data-jpa spring-rest