Rest Webservice中的表单验证

时间:2017-04-03 09:10:34

标签: java spring web-services rest jpa

我开始使用Spring和JPA在Java中构建我的第一个REST Web服务。

现在我正在尝试创建注册服务。我发送包含所有实体字段的请求时没有问题:

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@Entity
@Table(name = "users")  
public class User implements Serializable {

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;

@Enumerated(EnumType.STRING)
private Gender gender;

@Column(name = "email")
private String email;

@Column(name = "login")
private String login;

@Column(name = "password")
private String password;

@Column(name = "registration_date")
@CreatedDate
private LocalDateTime registrationDate;

@OneToMany(mappedBy = "bookOwner", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
private List<Book> bookList = new ArrayList<>();
}

但是在情况下该怎么做我希望我的注册表只有登录,密码和电子邮件字段,填写其余的用户详细信息是可选的 - 在确认注册后?

我考虑使用ModelMapper并为每个表单创建单独的类,但有没有更好的方法?

1 个答案:

答案 0 :(得分:0)

我自己使用提到的ModelMapper解决了问题。我粘贴我的代码。如果有人感兴趣,可能会有用。没有进行测试,但我的数据库看起来很好,并没有抛出异常。

 public class DTOMapper {
        private static final ModelMapper MAPPER = new ModelMapper();

        private DTOMapper(){}

        public static <S, T> T map(S source, Class<T> targetClass){
            return MAPPER.map(source, targetClass);
        }    
    }

@Service
@Transactional
public class SignUpService {

    private final UserRepository userRepository;

    @Autowired
    public SignUpService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User registerUser(SignUpForm form){
        if(userRepository.findByLogin(form.getLogin())!=null){
            throw new LoginAlreadyUsedException(form.getLogin());
        }

        if(userRepository.findByEmail(form.getEmail())!=null){
            throw new EmailAlreadyUsedException(form.getEmail());
        }

        User user = DTOMapper.map(form, User.class);

        User saved = userRepository.save(user);

        return DTOMapper.map(saved, User.class);
    }
}

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
public class SignUpForm implements Serializable {

    private static final long serialVersionUID = 1L;

    @NotEmpty
    @Size(min = 5)
    private String login;

    @NotEmpty
    @Size(min = 7)
    private String password;

    //todo email validation
    @NotEmpty
    private String email;
}


@RestController
public class SignUpController {
    private static final Logger log = LoggerFactory.getLogger(SignUpController.class);

    @Autowired
    private SignUpService signUpService;

    @PostMapping(value = "/signup")
    public ResponseEntity<?> addUser(@RequestBody @Valid SignUpForm form, BindingResult errors){

        if(errors.hasErrors()){
            throw new InvalidRequestException(errors);
        }

        signUpService.registerUser(form);
        return new ResponseEntity<>(form, HttpStatus.CREATED);
    }
}