本文整理汇总了Java中org.springframework.validation.BindingResult.addError方法的典型用法代码示例。如果您正苦于以下问题:Java BindingResult.addError方法的具体用法?Java BindingResult.addError怎么用?Java BindingResult.addError使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类org.springframework.validation.BindingResult
的用法示例。
在下文中一共展示了BindingResult.addError方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: saveUser
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* This method will be called on form submission, handling POST request for
* saving user in database. It also validates the user input
*/
@RequestMapping(value = {"/newuser"}, method = RequestMethod.POST)
public String saveUser(@Valid AdmUser user, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
/*
* Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation
* and applying it on field [sso] of Model class [User].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if (!userService.isUserSSOUnique(user.getUserId(), user.getEmail())) {
FieldError ssoError = new FieldError("user", "userId", messageSource.getMessage("non.unique.ssoId", new String[]{user.getEmail()}, Locale.getDefault()));
result.addError(ssoError);
return "registration";
}
userService.saveUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " registered successfully");
model.addAttribute("loggedinuser", getPrincipal());
//return "success";
return "registrationsuccess";
}
示例2: addFieldError
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
private void addFieldError(String objectName, String fieldName, String fieldValue, String errorCode, BindingResult result) {
LOGGER.debug(
"Adding field error object's: {} field: {} with error code: {}",
objectName,
fieldName,
errorCode
);
FieldError error = new FieldError(
objectName,
fieldName,
fieldValue,
false,
new String[]{errorCode},
new Object[]{},
errorCode
);
result.addError(error);
LOGGER.debug("Added field error: {} to binding result: {}", error, result);
}
示例3: atualizar
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* Atualiza os dados de um funcionário.
*
* @param id
* @param funcionarioDto
* @param result
* @return ResponseEntity<Response<FuncionarioDto>>
* @throws NoSuchAlgorithmException
*/
@PutMapping(value = "/{id}")
public ResponseEntity<Response<FuncionarioDto>> atualizar(@PathVariable("id") Long id,
@Valid @RequestBody FuncionarioDto funcionarioDto, BindingResult result) throws NoSuchAlgorithmException {
log.info("Atualizando funcionário: {}", funcionarioDto.toString());
Response<FuncionarioDto> response = new Response<FuncionarioDto>();
Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(id);
if (!funcionario.isPresent()) {
result.addError(new ObjectError("funcionario", "Funcionário não encontrado."));
}
this.atualizarDadosFuncionario(funcionario.get(), funcionarioDto, result);
if (result.hasErrors()) {
log.error("Erro validando funcionário: {}", result.getAllErrors());
result.getAllErrors().forEach(error -> response.getErrors().add(error.getDefaultMessage()));
return ResponseEntity.badRequest().body(response);
}
this.funcionarioService.persistir(funcionario.get());
response.setData(this.converterFuncionarioDto(funcionario.get()));
return ResponseEntity.ok(response);
}
示例4: saveUser
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "registration";
}
if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
result.addError(ssoError);
return "registration";
}
userService.saveUser(user);
model.addAttribute("success", "Użytkownik " + user.getFirstName() + " "+ user.getLastName() + " został zarejestrowany.");
model.addAttribute("loggedinuser", getPrincipal());
return "registrationsuccess";
}
示例5: saveUserAccount
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
@RequestMapping(value = { "/register" }, method = RequestMethod.POST)
public String saveUserAccount(@Valid User user, BindingResult result, ModelMap model) {
if (result.hasErrors() || result==null) {
return "register";
}
if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
result.addError(ssoError);
return "register";
}
userService.saveCustomerAccount(user);
model.addAttribute("success", "Użytkownik " + user.getFirstName() + " "+ user.getLastName() + " został zarejestrowany.");
model.addAttribute("loggedinuser", getPrincipal());
return "registrationsuccess";
}
示例6: register
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* Registers given user if there is no user with this username and all data is valid
* @param newUser AppUserDTO with details of the new user
*/
@RequestMapping(value="/register", method = RequestMethod.POST)
public String register(@Valid @ModelAttribute AppUserDTO newUser, BindingResult binding, RedirectAttributes attr, HttpSession session) {
LOGGER.debug("register(): registering user: {}", newUser.getUserName());
if(!binding.hasErrors()) {
try{
repositoryService.addUser(newUser);
attr.addFlashAttribute("registered", true);
}catch(DuplicateUserException de) {
LOGGER.debug("register(): duplicate user {}", newUser.getUserName());
String[] codes = new String[1];
codes[0] = "DuplicateUser";
binding.addError(new FieldError("newUser", "userName", newUser.getUserName(), false, codes, null, "*There is already an user with this name"));
attr.addFlashAttribute("org.springframework.validation.BindingResult.newUser", binding);
attr.addFlashAttribute("newUser", newUser);
}
} else
{
LOGGER.debug("register(): binding errors occured in the form: {}", newUser);
attr.addFlashAttribute("org.springframework.validation.BindingResult.newUser", binding);
attr.addFlashAttribute("newUser", newUser);
for(FieldError ferr:binding.getFieldErrors()) {
LOGGER.info("register(): field error: " + ferr.getDefaultMessage());
}
}
return "redirect:/register";
}
示例7: saveStudentUser
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* This method will be called on form submission, handling POST request for
* saving user in database. It also validates the user input
*/
@RequestMapping(value = {"/studentregistration"}, method = RequestMethod.POST)
public String saveStudentUser(@Valid StudentUser user, BindingResult result,
ModelMap model) {
if (result.hasErrors()) {
return "studentregistration";
}
/*
* Preferred way to achieve uniqueness of field [sso] should be implementing custom @Unique annotation
* and applying it on field [sso] of Model class [User].
*
* Below mentioned peace of code [if block] is to demonstrate that you can fill custom errors outside the validation
* framework as well while still using internationalized messages.
*
*/
if (!userService.isStudentUnique(user.getStudentUserId(), user.getEmail())) {
FieldError ssoError = new FieldError("studentuser", "email", messageSource.getMessage("non.unique.ssoId",
new String[]{user.getEmail()}, Locale.getDefault()));
result.addError(ssoError);
model.addAttribute("loggedinuser", getPrincipal());
return "studentregistration";
}
userService.saveUser(user);
model.addAttribute("success", "User " + user.getFirstName() + " " + user.getLastName() + " registered successfully");
model.addAttribute("loggedinuser", getPrincipal());
//return "success";
return "registrationsuccess";
}
示例8: validarFuncionario
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* Valida um funcionário, verificando se ele é existente e válido no
* sistema.
*
* @param lancamentoDto
* @param result
*/
private void validarFuncionario(LancamentoDto lancamentoDto, BindingResult result) {
if (lancamentoDto.getFuncionarioId() == null) {
result.addError(new ObjectError("funcionario", "Funcionário não informado."));
return;
}
log.info("Validando funcionário id {}: ", lancamentoDto.getFuncionarioId());
Optional<Funcionario> funcionario = this.funcionarioService.buscarPorId(lancamentoDto.getFuncionarioId());
if (!funcionario.isPresent()) {
result.addError(new ObjectError("funcionario", "Funcionário não encontrado. ID inexistente."));
}
}
示例9: converterDtoParaLancamento
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* Converte um LancamentoDto para uma entidade Lancamento.
*
* @param lancamentoDto
* @param result
* @return Lancamento
* @throws ParseException
*/
private Lancamento converterDtoParaLancamento(LancamentoDto lancamentoDto, BindingResult result) throws ParseException {
Lancamento lancamento = new Lancamento();
if (lancamentoDto.getId().isPresent()) {
Optional<Lancamento> lanc = this.lancamentoService.buscarPorId(lancamentoDto.getId().get());
if (lanc.isPresent()) {
lancamento = lanc.get();
} else {
result.addError(new ObjectError("lancamento", "Lançamento não encontrado."));
}
} else {
lancamento.setFuncionario(new Funcionario());
lancamento.getFuncionario().setId(lancamentoDto.getFuncionarioId());
}
lancamento.setDescricao(lancamentoDto.getDescricao());
lancamento.setLocalizacao(lancamentoDto.getLocalizacao());
lancamento.setData(this.dateFormat.parse(lancamentoDto.getData()));
if (EnumUtils.isValidEnum(TipoEnum.class, lancamentoDto.getTipo())) {
lancamento.setTipo(TipoEnum.valueOf(lancamentoDto.getTipo()));
} else {
result.addError(new ObjectError("tipo", "Tipo inválido."));
}
return lancamento;
}
示例10: validarDadosExistentes
import org.springframework.validation.BindingResult; //导入方法依赖的package包/类
/**
* Verifica se a empresa está cadastrada e se o funcionário não existe na base de dados.
*
* @param cadastroPFDto
* @param result
*/
private void validarDadosExistentes(CadastroPFDto cadastroPFDto, BindingResult result) {
Optional<Empresa> empresa = this.empresaService.buscarPorCnpj(cadastroPFDto.getCnpj());
if (!empresa.isPresent()) {
result.addError(new ObjectError("empresa", "Empresa não cadastrada."));
}
this.funcionarioService.buscarPorCpf(cadastroPFDto.getCpf())
.ifPresent(func -> result.addError(new ObjectError("funcionario", "CPF já existente.")));
this.funcionarioService.buscarPorEmail(cadastroPFDto.getEmail())
.ifPresent(func -> result.addError(new ObjectError("funcionario", "Email já existente.")));
}