小编imb*_*ond的帖子

在Spring应用程序中实现自定义验证的最佳方法是什么?

我(春季开发中的新手)正在为我的应用程序创建REST API,CRUD操作已成功实现,但现在我想实现服务器端验证。我还读到,可以通过几种方法来实施验证。

  1. 使用给定的注释-> @ notempty,@ email等...
  2. 使用自定义验证->扩展验证器

我想在我的应用程序中同时实现它们,

是遵循的好方法吗?

要么

还有其他方法可以实现验证吗?


控制者

@RestController
public class EmployeeController {

    @Autowired
    DataServices dataServices;

    @Autowired
    EmployeeValidator employeeValidator;

    @InitBinder
    protected void initBinder(WebDataBinder binder) {
        binder.addValidators(employeeValidator);
    }

    @RequestMapping(value = "/employee/", method = RequestMethod.POST)
    public ResponseEntity<Object> createUser(
            @Valid @RequestBody Employee employee,
            UriComponentsBuilder ucBuilder) throws Exception,
            DataIntegrityViolationException {

        if (dataServices.addEmployee(employee) == 0) {
            Error error = new Error(1, "Data integrity violation",
                    "Email id is already exists.");
            return new ResponseEntity<Object>(error, HttpStatus.CONFLICT);
        }

        HttpHeaders headers = new HttpHeaders();
        headers.setLocation(ucBuilder.path("/employee/{id}")
                .buildAndExpand(employee.getId()).toUri()); …
Run Code Online (Sandbox Code Playgroud)

java validation spring

5
推荐指数
1
解决办法
1万
查看次数

标签 统计

java ×1

spring ×1

validation ×1