Java Code Examples for org.springframework.validation.BindingResult#getAllErrors()

The following examples show how to use org.springframework.validation.BindingResult#getAllErrors() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: LinksAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
@ResponseBody
@PostMapping(value = "/update_links")
public DataVo updateFriendLink(@Valid Links links, BindingResult result) {
	DataVo data = DataVo.failure("操作失败");
       try {
           if (result.hasErrors()) {
               List<ObjectError> list = result.getAllErrors();
               for (ObjectError error : list) {
                   return DataVo.failure(error.getDefaultMessage());
               }
               return null;
           }
           if (!NumberUtils.isNumber(links.getId().toString())) {
               return DataVo.failure("友情链接ID参数错误!");
           }
           links.setLinkName(links.getLinkName().trim());
           links.setLinkUrl(links.getLinkUrl().trim());
           data = linksService.updateLinksById(links);
       } catch (Exception e) {
           data = DataVo.failure(e.getMessage());
           log.warn(e.getMessage());
       }
	return data;
}
 
Example 2
Source File: UserController.java    From FS-Blog with Apache License 2.0 6 votes vote down vote up
/**
 * 前台用户登录
 * 表单提交
 */
@PostMapping("/userlogin.f")
public String fFrontUserLogin(HttpServletRequest request, Model model, @Valid UserLoginForm loginForm, BindingResult bindingResult) throws Exception {
  if (bindingResult.hasErrors()) {
    List<ObjectError> errors = bindingResult.getAllErrors();
    addModelAtt(model, VIEW_MSG, errors.get(0).getDefaultMessage());
    return "userlogin";
  }
  User user = mUserService.loginAuthentication(loginForm);
  if (null != user) {
    mUserService.joinSession(request, user);
    return "redirect:/";
  }
  addModelAtt(model, VIEW_MSG, "用户名或密码错误");
  return "userlogin";
}
 
Example 3
Source File: TaskDefineController.java    From batch-scheduler with MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.PUT)
@ResponseBody
public String update(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    RetMsg retMsg = taskDefineService.update(parse(request));
    if (!retMsg.checkCode()) {
        response.setStatus(retMsg.getCode());
        return Hret.error(retMsg);
    }
    return Hret.success(retMsg);
}
 
Example 4
Source File: TdsErrorHandling.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ExceptionHandler(BindException.class)
public ResponseEntity<String> handle(BindException ex) {
  BindingResult validationResult = ex.getBindingResult();
  List<ObjectError> errors = validationResult.getAllErrors();
  Formatter f = new Formatter();
  f.format("Validation errors: ");
  for (ObjectError err : errors) {
    f.format(" %s%n", err.getDefaultMessage());
  }

  logger.warn(f.toString(), ex);

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.TEXT_PLAIN);
  return new ResponseEntity<>(f.toString(), responseHeaders, HttpStatus.BAD_REQUEST);
}
 
Example 5
Source File: BrandAdminController.java    From FlyCms with MIT License 6 votes vote down vote up
@PostMapping("/brand_category_save")
@ResponseBody
public DataVo addBrandCategory(@Valid BrandCategory category, BindingResult result){
    DataVo data = DataVo.failure("操作失败");
    try {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                return DataVo.failure(error.getDefaultMessage());
            }
            return null;
        }
        data = brandService.addBrandCategory(category);
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}
 
Example 6
Source File: CategoryController.java    From stone with GNU General Public License v3.0 6 votes vote down vote up
/**
 * 新增/修改分类目录
 *
 * @param category category对象
 *
 * @return JsonResult
 */
@PostMapping(value = "/save")
@ResponseBody
public JsonResult saveCategory(@Valid Category category, BindingResult result) {
    if (result.hasErrors()) {
        for (ObjectError error : result.getAllErrors()) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), error.getDefaultMessage());
        }
    }
    final Category tempCategory = categoryService.findByCateUrl(category.getCateUrl());
    if (null != category.getCateId()) {
        if (null != tempCategory && !category.getCateId().equals(tempCategory.getCateId())) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists"));
        }
    } else {
        if (null != tempCategory) {
            return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.url-is-exists"));
        }
    }
    category = categoryService.save(category);
    if (null == category) {
        return new JsonResult(ResultCodeEnum.FAIL.getCode(), localeMessageUtil.getMessage("code.admin.common.save-failed"));
    }
    return new JsonResult(ResultCodeEnum.SUCCESS.getCode(), localeMessageUtil.getMessage("code.admin.common.save-success"));
}
 
Example 7
Source File: TaskDefineController.java    From batch-scheduler with MIT License 6 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "新增任务信息", notes = "向系统中添加新的任务,任务必须是存储过程,shell脚本,cmd脚本,可执行jar包,二进制文件中的一种")
public String add(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) {
    // 校验参数信息
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    RetMsg retMsg = taskDefineService.add(parse(request));
    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }
    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
 
Example 8
Source File: UserController.java    From songjhh_blog with Apache License 2.0 6 votes vote down vote up
@RequestMapping(value = "/register",method = RequestMethod.POST)
public String register(Model model,
                       @Valid UserCustom userCustom, BindingResult bindingResult) {
    if(bindingResult.hasErrors()) {
        List<ObjectError> allErrors = bindingResult.getAllErrors();
        for(ObjectError objectError:allErrors) {
            //输出错误信息
            System.out.println(objectError.getDefaultMessage());
        }
        model.addAttribute("allErrors", allErrors);
        model.addAttribute("user", userCustom);
        return "/user/register";
    }

    if (userService.getByUserName(userCustom.getUsername()) == null) {
        userService.insertUser(userCustom);
        userService.giveRole(userCustom,3);//3为普通用户 待改善
        return "redirect:/";
    } else {
        model.addAttribute("user", userCustom);
        model.addAttribute("errormessage", "userName has been registered!");
        return "/user/register";
    }
}
 
Example 9
Source File: NewAccountControllerTest.java    From attic-rave with Apache License 2.0 6 votes vote down vote up
@Test
public void create_ValidFormSubmitted() {
	final Model model = createNiceMock(Model.class);
	final UserForm User = new UserForm();
	final BindingResult errors = createNiceMock(BindingResult.class);
	final String username = "username"; //Username not specified
	final String password = "password"; //Password not specified
	final String confirmPassword = password; //Confirm password not specified
	List<ObjectError> errorList = new ArrayList<ObjectError>();

	User.setUsername(username);
	User.setPassword(password);
	User.setConfirmPassword(confirmPassword);

	expect(errors.hasErrors()).andReturn(false).anyTimes();
	expect(errors.getAllErrors()).andReturn(errorList).anyTimes();
	replay(errors);

	String result = newAccountController.create(User, errors, model, request, redirectAttributes);
	errorList = errors.getAllErrors();

	assertThat(errorList.size(), CoreMatchers.equalTo(0));
	assertThat(result, CoreMatchers.equalTo(ViewNames.REDIRECT_LOGIN));
}
 
Example 10
Source File: PageBulkDeleteController.java    From wallride with Apache License 2.0 5 votes vote down vote up
@RequestMapping
public String delete(
		@Valid @ModelAttribute("form") PageBulkDeleteForm form,
		BindingResult errors,
		String query,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addAttribute("query", query);

	if (!form.isConfirmed()) {
		errors.rejectValue("confirmed", "Confirmed");
	}
	if (errors.hasErrors()) {
		logger.debug("Errors: {}", errors);
		return "redirect:/_admin/{language}/pages/index";
	}
	
	Collection<Page> pages = null;
	try {
		pages = pageService.bulkDeletePage(form.buildPageBulkDeleteRequest(), errors);
	}
	catch (ValidationException e) {
		if (errors.hasErrors()) {
			logger.debug("Errors: {}", errors);
			return "redirect:/_admin/{language}/pages/index";
		}
		throw e;
	}
	
	List<String> errorMessages = null;
	if (errors.hasErrors()) {
		errorMessages = new ArrayList<>();
		for (ObjectError error : errors.getAllErrors()) {
			errorMessages.add(messageSourceAccessor.getMessage(error));
		}
	}
	
	redirectAttributes.addFlashAttribute("deletedPages", pages);
	redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
	return "redirect:/_admin/{language}/pages/index";
}
 
Example 11
Source File: SysDomainController.java    From batch-scheduler with MIT License 5 votes vote down vote up
/**
 * 新增域
 */
@RequestMapping(method = RequestMethod.POST)
@ResponseBody
@ApiOperation(value = "新增域信息", notes = "添加新的域信息,新增的域默认授权给创建人")
@ApiImplicitParam(name = "domain_id", value = "域编码", required = true, dataType = "String")
public String add(@Validated SysDomainInfoAddParamVo paramVo,
                  BindingResult bindingResult,
                  HttpServletResponse response,
                  HttpServletRequest request) {
    if (bindingResult.hasErrors()) {
        for (ObjectError m : bindingResult.getAllErrors()) {
            response.setStatus(421);
            return Hret.error(421, m.getDefaultMessage(), null);
        }
    }

    DomainEntity domainEntity = validParam(paramVo);
    String userId = JwtService.getConnUser(request).getUserId();
    domainEntity.setDomain_modify_user(userId);
    domainEntity.setCreate_user_id(userId);

    RetMsg retMsg = domainService.add(domainEntity);

    if (retMsg.checkCode()) {
        return Hret.success(retMsg);
    }

    response.setStatus(retMsg.getCode());
    return Hret.error(retMsg);
}
 
Example 12
Source File: ControllerExceptionHandleAdvice.java    From seppb with MIT License 5 votes vote down vote up
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseBody
public GenericResponse valid(MethodArgumentNotValidException e) {
    BindingResult bindingResult = e.getBindingResult();
    List<ObjectError> allErrors = bindingResult.getAllErrors();
    List<String> errorMessages = allErrors.stream().map(ObjectError::getDefaultMessage).collect(toList());
    String message = StringUtils.join(errorMessages, ";");
    return GenericResponse.CLIENT_ERROR.setMessage(message);
}
 
Example 13
Source File: NewAccountControllerTest.java    From attic-rave with Apache License 2.0 5 votes vote down vote up
@Test
public void create_UsernameNotSpecified() {
	final Model model = createNiceMock(Model.class);
	final UserForm User = new UserForm();
	final BindingResult errors = createNiceMock(BindingResult.class);
	final String username = ""; //no username specified
	final String password = "password";
	final String confirmPassword = password;
	List<ObjectError> errorList = new ArrayList<ObjectError>();
	final ObjectError error = new ObjectError("username.required", "Username required");

	User.setUsername(username);
	User.setPassword(password);
	User.setConfirmPassword(confirmPassword);

	errorList.add(error);

	expect(errors.hasErrors()).andReturn(true).anyTimes();
	expect(errors.getAllErrors()).andReturn(errorList).anyTimes();
	replay(errors);

       replay(model);
	String result = newAccountController.create(User, errors, model, request, redirectAttributes);
	errorList = errors.getAllErrors();

	assertThat(errorList.size(), CoreMatchers.equalTo(1));
	assertThat(errorList.get(0).getDefaultMessage(), CoreMatchers.equalTo("Username required"));
	assertThat(result, CoreMatchers.equalTo(ViewNames.NEW_ACCOUNT));
}
 
Example 14
Source File: MessageController.java    From spring-boot-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
@PostMapping
public ModelAndView create(@Valid Message message, BindingResult result, RedirectAttributes redirect) {
    if (result.hasErrors()) {
        return new ModelAndView("messages/form", "formErrors", result.getAllErrors());
    }
    message = this.messageRepository.save(message);
    redirect.addFlashAttribute("globalMessage", "view.success");
    return new ModelAndView("redirect:/{message.id}", "message.id", message.getId());
}
 
Example 15
Source File: ClienteController.java    From spring-boot-greendogdelivery-casadocodigo with GNU General Public License v3.0 5 votes vote down vote up
@PostMapping(params = "form")
public ModelAndView create(@Valid Cliente cliente,BindingResult result,RedirectAttributes redirect) {
	if (result.hasErrors()) { return new ModelAndView(CLIENTE_URI + "form","formErrors",result.getAllErrors()); }
	cliente = this.clienteRepository.save(cliente);
	redirect.addFlashAttribute("globalMessage","Cliente gravado com sucesso");
	return new ModelAndView("redirect:/" + CLIENTE_URI + "{cliente.id}","cliente.id",cliente.getId());
}
 
Example 16
Source File: CouponController.java    From kakaopay-coupon with MIT License 5 votes vote down vote up
@ResponseStatus(HttpStatus.CREATED)
@RequestMapping(value = "/coupon", method = RequestMethod.POST, consumes = "application/json; charset=UTF-8")
public Coupon createCoupon(@RequestBody @Valid CouponCreateDTO couponCreateDTO, BindingResult error) {
    if (error.hasErrors()) {
        for (ObjectError err :error.getAllErrors()) {
            if (InvalidEmailException.errorCode.equals(err.getDefaultMessage())) {
                log.info("CouponController - createCoupon : invalid email");
                throw new InvalidEmailException("Fail to create Coupon. Email format is invalid.");
            }
        }
    }
    return couponService.create(couponCreateDTO);
}
 
Example 17
Source File: BaseController.java    From WeBASE-Front with Apache License 2.0 5 votes vote down vote up
private String getParamValidFaildMessage(BindingResult bindingResult) {
    List<ObjectError> errorList = bindingResult.getAllErrors();
    log.info("errorList:{}", JsonUtils.toJSONString(errorList));
    if (errorList == null) {
        log.warn("onWarning:errorList is empty!");
        return null;
    }

    ObjectError objectError = errorList.get(0);
    if (objectError == null) {
        log.warn("onWarning:objectError is empty!");
        return null;
    }
    return objectError.getDefaultMessage();
}
 
Example 18
Source File: UserBulkDeleteController.java    From wallride with Apache License 2.0 4 votes vote down vote up
@RequestMapping
public String delete(
		@Valid @ModelAttribute("form") UserBulkDeleteForm form,
		BindingResult errors,
		String query,
		AuthorizedUser authorizedUser,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addAttribute("query", query);

	if (!form.isConfirmed()) {
		errors.rejectValue("confirmed", "Confirmed");
	}
	if (errors.hasErrors()) {
		logger.debug("Errors: {}", errors);
		return "redirect:/_admin/user/";
	}
	
	Collection<User> users = null;
	try {
		users = userService.bulkDeleteUser(form.buildUserBulkDeleteRequest(), errors);
	}
	catch (ValidationException e) {
		if (errors.hasErrors()) {
			logger.debug("Errors: {}", errors);
			return "redirect:/_admin/user/";
		}
		throw e;
	}
	
	List<String> errorMessages = null;
	if (errors.hasErrors()) {
		errorMessages = new ArrayList<>();
		for (ObjectError error : errors.getAllErrors()) {
			errorMessages.add(messageSourceAccessor.getMessage(error));
		}
	}
	
	redirectAttributes.addFlashAttribute("deletedArticles", users);
	redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
	return "redirect:/_admin/{language}/users/index";
}
 
Example 19
Source File: TagBulkDeleteController.java    From wallride with Apache License 2.0 4 votes vote down vote up
@RequestMapping
public String delete(
		@Valid @ModelAttribute("form") TagBulkDeleteForm form,
		BindingResult errors,
		String query,
		AuthorizedUser authorizedUser,
		RedirectAttributes redirectAttributes) {
	redirectAttributes.addAttribute("query", query);

	if (!form.isConfirmed()) {
		errors.rejectValue("confirmed", "Confirmed");
	}
	if (errors.hasErrors()) {
		logger.debug("Errors: {}", errors);
		return "redirect:/_admin/{language}/tags/index";
	}
	
	Collection<Tag> tags = null;
	try {
		tags = tagService.bulkDeleteTag(form.buildTagBulkDeleteRequest(), errors);
	}
	catch (ValidationException e) {
		if (errors.hasErrors()) {
			logger.debug("Errors: {}", errors);
			return "redirect:/_admin/{language}/tags/index";
		}
		throw e;
	}
	
	List<String> errorMessages = null;
	if (errors.hasErrors()) {
		errorMessages = new ArrayList<>();
		for (ObjectError error : errors.getAllErrors()) {
			errorMessages.add(messageSourceAccessor.getMessage(error));
		}
	}
	
	redirectAttributes.addFlashAttribute("deletedTags", tags);
	redirectAttributes.addFlashAttribute("errorMessages", errorMessages);
	return "redirect:/_admin/{language}/tags/index";
}
 
Example 20
Source File: UserController.java    From FlyCms with MIT License 4 votes vote down vote up
@PostMapping("/ucenter/account_update")
@ResponseBody
public DataVo updateUserAccount(@Valid User user, BindingResult result){
    DataVo data = DataVo.failure("操作失败");
    try {
        if (result.hasErrors()) {
            List<ObjectError> list = result.getAllErrors();
            for (ObjectError error : list) {
                return DataVo.failure(error.getDefaultMessage());
            }
            return null;
        }
        if(!StringUtils.isNumeric(user.getUserId().toString())){
            return data=DataVo.failure("请勿非法传递数据!");
        }
        if(!user.getUserId().equals(getUser().getUserId())){
            return data=DataVo.failure("请勿非法传递数据!");
        }
        if(!getUser().getUserId().equals(user.getUserId())){
            return data=DataVo.failure("只能修改属于自己的基本信息!");
        }
        if(StringUtils.isBlank(user.getNickName())){
            return data=DataVo.failure("昵称不能为空!");
        }
        if(user.getBirthday()==null || "".equals(user.getBirthday())){
            return data=DataVo.failure("请选择您的生日日期!");
        }
        if(DateUtils.isValidDate(user.getBirthday().toString())){
            return data=DataVo.failure("生日日期格式错误!");
        }
        if(user.getProvince()==0){
            return data=DataVo.failure("省份未选择!");
        }
        if(user.getCity()==0){
            return data=DataVo.failure("地区为选择!");
        }

        data = userService.updateUserAccount(user);
    } catch (Exception e) {
        data = DataVo.failure(e.getMessage());
    }
    return data;
}