Here are the examples of the java api org.springframework.validation.BindingResult.getFieldError() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
149 Examples
19
View Source File : AccountController.java
License : Apache License 2.0
Project Creator : Zoctan
License : Apache License 2.0
Project Creator : Zoctan
@PostMapping
public Result register(@RequestBody @Valid final AccountDto account, final BindingResult bindingResult) {
// {"name":"123456", "preplacedword":"123456", "email": "[email protected]"}
if (bindingResult.hasErrors()) {
// noinspection ConstantConditions
final String msg = bindingResult.getFieldError().getDefaultMessage();
return ResultGenerator.genFailedResult(msg);
} else {
this.accountService.save(account);
return this.getToken(account.getName());
}
}
19
View Source File : UserController.java
License : Apache License 2.0
Project Creator : zhuoqianmingyue
License : Apache License 2.0
Project Creator : zhuoqianmingyue
/**
* 添加用户
*/
@PostMapping()
public User add(@Valid User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
String defaultMessage = bindingResult.getFieldError().getDefaultMessage();
System.out.println(defaultMessage);
return null;
}
log.info("springboot添加用户成功:" + "name:{},age:{}", user.getName(), user.getAge());
return user;
}
19
View Source File : BaseCrudController.java
License : MIT License
Project Creator : ZhiYiDai
License : MIT License
Project Creator : ZhiYiDai
/**
* 增加
*
* @param m
* @return
*/
@ResponseBody
@RequestMapping(value = "/create", method = RequestMethod.POST)
@Permission(value = "create")
public ServiceResult create(@Valid T m, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new ServiceResult(false).setMessage(bindingResult.getFieldError().getDefaultMessage());
}
m.setCreatorId(getLoginUserId());
ServiceResult beforeResult = createBefore(m);
if (beforeResult != null) {
return beforeResult;
}
ServiceResult result = getService().create(m);
createAfter(m, result);
return result;
}
19
View Source File : RestApiController.java
License : GNU General Public License v3.0
Project Creator : zhangyd-c
License : GNU General Public License v3.0
Project Creator : zhangyd-c
@PostMapping("/autoLink")
@BussinessLog(value = "自助申请友链", platform = PlatformEnum.WEB)
public ResponseVO autoLink(@Validated Link link, BindingResult bindingResult) {
log.info("申请友情链接......");
log.info(JSON.toJSONString(link));
if (bindingResult.hasErrors()) {
return ResultUtil.error(bindingResult.getFieldError().getDefaultMessage());
}
try {
sysLinkService.autoLink(link);
} catch (ZhydLinkException e) {
log.error("客户端自助申请友链发生异常", e);
return ResultUtil.error(e.getMessage());
}
return ResultUtil.success("已成功添加友链,祝您生活愉快!");
}
19
View Source File : CommonResult.java
License : MIT License
Project Creator : yzsunlei
License : MIT License
Project Creator : yzsunlei
/**
* 参数验证失败使用
* @param result 错误信息
*/
public CommonResult validateFailed(BindingResult result) {
validateFailed(result.getFieldError().getDefaultMessage());
return this;
}
19
View Source File : BindingResultUtil.java
License : Apache License 2.0
Project Creator : xunibidev
License : Apache License 2.0
Project Creator : xunibidev
public static MessageResult validate(BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
String message = bindingResult.getFieldError().getDefaultMessage();
return MessageResult.error(500, message);
} else {
return null;
}
}
19
View Source File : UserController.java
License : MIT License
Project Creator : wu-boy
License : MIT License
Project Creator : wu-boy
@ApiOperation("新增")
@PostMapping("create")
public BaseResult create(@RequestBody @Validated CreateUserDto dto, BindingResult bindingResult) {
BaseResult result = new BaseResult();
// 校验参数
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
log.error("新增用户参数错误:{}", fieldError.getDefaultMessage());
result.setCode(HttpStatus.BAD_REQUEST.value());
result.setMessage(fieldError.getDefaultMessage());
return result;
}
try {
User user = new User();
BeanUtils.copyProperties(dto, user);
log.info("接收到用户{},{}", user.getUsername(), user.getPreplacedword());
result.setData(user);
} catch (Exception e) {
result.setCode(HttpStatus.INTERNAL_SERVER_ERROR.value());
result.setMessage(e.getMessage());
log.error("新增用户错误{}", e.getMessage());
e.printStackTrace();
}
return result;
}
19
View Source File : ModelResultMatchers.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* replacedert a field error code for a model attribute using a {@link org.hamcrest.Matcher}.
* @since 4.1
*/
public <T> ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final Matcher<? super String> matcher) {
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
replacedertTrue("No errors for attribute: [" + name + "]", result.hasErrors());
FieldError fieldError = result.getFieldError(fieldName);
if (fieldError == null) {
fail("No errors for field '" + fieldName + "' of attribute '" + name + "'");
}
String code = fieldError.getCode();
replacedertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
};
}
19
View Source File : ModelResultMatchers.java
License : MIT License
Project Creator : Vip-Augus
License : MIT License
Project Creator : Vip-Augus
/**
* replacedert a field error code for a model attribute using exact String match.
* @since 4.1
*/
public ResultMatcher attributeHasFieldErrorCode(final String name, final String fieldName, final String error) {
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
replacedertTrue("No errors for attribute '" + name + "'", result.hasErrors());
FieldError fieldError = result.getFieldError(fieldName);
if (fieldError == null) {
fail("No errors for field '" + fieldName + "' of attribute '" + name + "'");
}
String code = fieldError.getCode();
replacedertTrue("Expected error code '" + error + "' but got '" + code + "'", error.equals(code));
};
}
19
View Source File : GlobalExceptionHandler.java
License : MIT License
Project Creator : tongji4m3
License : MIT License
Project Creator : tongji4m3
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.clreplaced)
public CommonResult handleValidException(MethodArgumentNotValidException e) {
// springboot的参数校验失败时,会自动抛出该异常,只要全局处理该异常依然可以得到校验失败信息。
BindingResult bindingResult = e.getBindingResult();
String message = null;
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
if (fieldError != null) {
message = fieldError.getField() + fieldError.getDefaultMessage();
}
}
return CommonResult.validateFailed(message);
}
19
View Source File : GlobalExceptionHandler.java
License : MIT License
Project Creator : tongji4m3
License : MIT License
Project Creator : tongji4m3
@ResponseBody
@ExceptionHandler(value = MethodArgumentNotValidException.clreplaced)
public CommonResult handleValidException(MethodArgumentNotValidException e) {
BindingResult bindingResult = e.getBindingResult();
String message = null;
if (bindingResult.hasErrors()) {
FieldError fieldError = bindingResult.getFieldError();
if (fieldError != null) {
message = fieldError.getField() + fieldError.getDefaultMessage();
}
}
return CommonResult.validateFailed(message);
}
19
View Source File : RequestResponseBodyMethodProcessorMockTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void resolveArgumentNotValid() throws Exception {
replacedertThatExceptionOfType(MethodArgumentNotValidException.clreplaced).isThrownBy(() -> testResolveArgumentWithValidation(new SimpleBean(null))).satisfies(ex -> {
BindingResult bindingResult = ex.getBindingResult();
replacedertThat(bindingResult.getObjectName()).isEqualTo("simpleBean");
replacedertThat(bindingResult.getErrorCount()).isEqualTo(1);
replacedertThat(bindingResult.getFieldError("name")).isNotNull();
});
}
19
View Source File : RequestPartMethodArgumentResolverTests.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
@Test
public void resolveRequestPartNotValid() throws Exception {
replacedertThatExceptionOfType(MethodArgumentNotValidException.clreplaced).isThrownBy(() -> testResolveArgument(new SimpleBean(null), paramValidRequestPart)).satisfies(ex -> {
BindingResult bindingResult = ex.getBindingResult();
replacedertThat(bindingResult.getObjectName()).isEqualTo("requestPart");
replacedertThat(bindingResult.getErrorCount()).isEqualTo(1);
replacedertThat(bindingResult.getFieldError("name")).isNotNull();
});
}
19
View Source File : ModelResultMatchers.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* replacedert a field error code for a model attribute using a {@link org.hamcrest.Matcher}.
* @since 4.1
*/
public ResultMatcher attributeHasFieldErrorCode(String name, String fieldName, Matcher<? super String> matcher) {
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
replacedertTrue("No errors for attribute '" + name + "'", result.hasErrors());
FieldError fieldError = result.getFieldError(fieldName);
replacedertNotNull("No errors for field '" + fieldName + "' of attribute '" + name + "'", fieldError);
String code = fieldError.getCode();
replacedertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
};
}
19
View Source File : ModelResultMatchers.java
License : Apache License 2.0
Project Creator : SourceHot
License : Apache License 2.0
Project Creator : SourceHot
/**
* replacedert a field error code for a model attribute using exact String match.
* @since 4.1
*/
public ResultMatcher attributeHasFieldErrorCode(String name, String fieldName, String error) {
return mvcResult -> {
ModelAndView mav = getModelAndView(mvcResult);
BindingResult result = getBindingResult(mav, name);
replacedertTrue("No errors for attribute '" + name + "'", result.hasErrors());
FieldError fieldError = result.getFieldError(fieldName);
replacedertNotNull("No errors for field '" + fieldName + "' of attribute '" + name + "'", fieldError);
String code = fieldError.getCode();
replacedertEquals("Field error code", error, code);
};
}
19
View Source File : ResultUtil.java
License : MIT License
Project Creator : qunarcorp
License : MIT License
Project Creator : qunarcorp
/**
* 执行传递过来的类中的RUN方法 并根据校验信息返回成功或失败
*/
public static Result validAndRun(BindingResult bindingResult, BaseController object) throws Exception {
if (bindingResult.hasErrors()) {
return error(-2, bindingResult.getFieldError().getDefaultMessage());
}
return success(object.run());
}
19
View Source File : PubRoleController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 保存角色
*/
@RequiresPermissions("pubRole:add")
@PostMapping("/save")
public String save(@Validated PubRolePO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/pubRole/create";
} else {
try {
roleService.save(po);
AlertMessage.success("保存角色成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/pubRole/list";
}
19
View Source File : PubRoleController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 修改角色
*/
@RequiresPermissions("pubRole:edit")
@PostMapping("/update")
public String edit(@Validated PubRolePO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/pubRole/edit";
} else {
try {
roleService.edit(po);
AlertMessage.success("修改角色成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/pubRole/list";
}
19
View Source File : PubParamController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 更新参数
*/
@RequiresPermissions("pubParam:edit")
@PostMapping("/update")
public String update(@Validated PubParamPO param, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
} else {
try {
paramService.modify(param);
AlertMessage.success("更新参数成功").flashAttribute(ra);
return "redirect:/pubParam/list";
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/pubParam/edit?code=" + param.getCode();
}
19
View Source File : PayWayController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 保存
*/
@RequiresPermissions("payWay:add")
@PostMapping("/save")
public String save(@Validated PayWayPO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/payWay/create";
} else {
try {
payWayService.save(po);
AlertMessage.success("保存成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/payWay/list";
}
19
View Source File : PayWayController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 修改
*/
@RequiresPermissions("payWay:edit")
@PostMapping("/update")
public String edit(@Validated PayWayPO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/payWay/edit";
} else {
try {
payWayService.modify(po);
AlertMessage.success("修改成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/payWay/list";
}
19
View Source File : PayTypeController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 修改
*/
@RequiresPermissions("payType:edit")
@PostMapping("/update")
public String edit(@Validated PayTypePO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/payType/edit";
} else {
try {
payTypeService.modify(po);
AlertMessage.success("修改成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/payType/list";
}
19
View Source File : PayTypeController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 保存
*/
@RequiresPermissions("payType:add")
@PostMapping("/save")
public String save(@Validated PayTypePO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/payType/create";
} else {
try {
payTypeService.save(po);
AlertMessage.success("保存成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/payType/list";
}
19
View Source File : PayProductController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 修改
*/
@RequiresPermissions("payProduct:edit")
@PostMapping("/update")
public String edit(@Validated PayProductPO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/payProduct/edit";
} else {
try {
payProductService.modify(po);
AlertMessage.success("修改成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/payProduct/list";
}
19
View Source File : PayProductController.java
License : Apache License 2.0
Project Creator : pleuvoir
License : Apache License 2.0
Project Creator : pleuvoir
/**
* 保存
*/
@RequiresPermissions("payProduct:add")
@PostMapping("/save")
public String save(@Validated PayProductPO po, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
if (bindingResult.getGlobalError() != null) {
AlertMessage.error(bindingResult.getGlobalError()).flashAttribute(ra);
} else if (bindingResult.getFieldError() != null) {
AlertMessage.error(bindingResult.getFieldError()).flashAttribute(ra);
}
return "redirect:/payProduct/create";
} else {
try {
payProductService.save(po);
AlertMessage.success("保存成功").flashAttribute(ra);
} catch (BusinessException e) {
AlertMessage.error(e.getMessage()).flashAttribute(ra);
}
}
return "redirect:/payProduct/list";
}
19
View Source File : NewBeeMallExceptionHandler.java
License : GNU General Public License v3.0
Project Creator : newbee-ltd
License : GNU General Public License v3.0
Project Creator : newbee-ltd
@ExceptionHandler(BindException.clreplaced)
public Object bindException(BindException e) {
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
19
View Source File : NewBeeMallExceptionHandler.java
License : GNU General Public License v3.0
Project Creator : newbee-ltd
License : GNU General Public License v3.0
Project Creator : newbee-ltd
@ExceptionHandler(MethodArgumentNotValidException.clreplaced)
public Object bindException(MethodArgumentNotValidException e) {
Result result = new Result();
result.setResultCode(510);
BindingResult bindingResult = e.getBindingResult();
result.setMessage(Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
return result;
}
19
View Source File : SellerProductController.java
License : Apache License 2.0
Project Creator : miraclestatus
License : Apache License 2.0
Project Creator : miraclestatus
@PostMapping("/save")
public ModelAndView save(@Valid ProductForm form, BindingResult bindingResult, Map<String, Object> map) {
if (bindingResult.hasErrors()) {
// 返回错误页面
map.put("msg", bindingResult.getFieldError().getDefaultMessage());
map.put("url", "/seller/product/index");
return new ModelAndView("common/error", map);
}
ProductInfo productInfo = new ProductInfo();
try {
// productInfo.setProductName(form.getProductName());
if (!StringUtils.isEmpty(form.getProductId())) {
// 有ProductId 修改
productInfo = productService.findOne(form.getProductId());
} else {
// 新增 生成一个id
form.setProductId(KeyUtil.genUniqueKey());
}
BeanUtils.copyProperties(form, productInfo);
productService.save(productInfo);
} catch (SellException exception) {
map.put("msg", exception.getMessage());
map.put("url", "/seller/product/index");
return new ModelAndView("common/error", map);
}
map.put("url", "/seller/product/list");
return new ModelAndView("common/success", map);
}
19
View Source File : ApproveProcessController.java
License : GNU General Public License v3.0
Project Creator : lovelifeming
License : GNU General Public License v3.0
Project Creator : lovelifeming
@ApiOperation("开始流程(创建并执行流程)")
@PostMapping("start")
public ResultSet startProcess(@RequestBody @Valid StartVO startVO, BindingResult results) {
if (results.hasErrors())
return ResultSet.fail(results.getFieldError().getDefaultMessage());
HashMap<String, Object> processVariable = new HashMap<>();
processVariable.put("handler", startVO.getUserId());
processVariable.put("userId", startVO.getUserId());
processVariable.put("approve", startVO.getApprove());
processVariable.put("businessKey", startVO.getBusinessKey());
Authentication.setAuthenticatedUserId(startVO.getUserId());
String processId = service.startProcessInstanceByKey(PROCESS_NAME, startVO.getBusinessKey(), processVariable).getId();
Authentication.setAuthenticatedUserId(null);
log.info("startProcess创建流程 {},userId={},nextUserId={},approve={},verify={},businessKey={}", PROCESS_NAME, startVO.getUserId(), startVO.getNextUserId(), startVO.getApprove(), startVO.getVerify(), startVO.getBusinessKey());
service.setProcessVariable(processId, "verify", startVO.getVerify());
String taskId = service.getOneTaskIdByProcessId(processId);
HashMap<String, Object> map = new HashMap<>();
map.put("handler", startVO.getNextUserId());
map.put("userId", startVO.getNextUserId());
map.put("approve", startVO.getApprove());
map.put("due", "no");
service.complete(taskId, map);
log.info("startProcess成功执行流程,processId={},taskId={},businessKey={}", processId, taskId, startVO.getBusinessKey());
Task task = service.getOneTaskByProcessId(processId);
if (task == null) {
return ResultSet.success("任务已完成");
}
ProcessInfo info = new ProcessInfo(task.getId(), task.getProcessInstanceId(), startVO.getBusinessKey());
return ResultSet.success(info);
}
19
View Source File : ApproveProcessController.java
License : GNU General Public License v3.0
Project Creator : lovelifeming
License : GNU General Public License v3.0
Project Creator : lovelifeming
@ApiOperation("过期流程")
@PostMapping("pastDue")
public ResultSet pastDue(@RequestBody @Valid SuccessVO successVO, BindingResult results) {
if (results.hasErrors())
return ResultSet.fail(results.getFieldError().getDefaultMessage());
Task task = service.getOneTaskByTaskId(successVO.getTaskId());
if (task == null) {
return ResultSet.fail("任务不存在");
}
HashMap<String, Object> map = new HashMap<>();
map.put("handler", successVO.getUserId());
map.put("userId", successVO.getNextUserId());
map.put("due", "yes");
ProcessInstance instance = service.getProcessByProcessId(task.getProcessInstanceId());
service.complete(successVO.getTaskId(), map);
log.info("pastDue成功执行流程,userId={},nextUserId={},processId={},taskId={},businessKey={}", successVO.getUserId(), successVO.getNextUserId(), instance.getId(), successVO.getTaskId(), instance.getBusinessKey());
Task task1 = service.getOneTaskByProcessId(task.getProcessInstanceId());
ProcessInfo info = new ProcessInfo(task1.getId(), task1.getProcessInstanceId(), instance.getBusinessKey());
return ResultSet.success(info);
}
19
View Source File : ApproveProcessController.java
License : GNU General Public License v3.0
Project Creator : lovelifeming
License : GNU General Public License v3.0
Project Creator : lovelifeming
@ApiOperation("执行同意流程(职员)")
@PostMapping("successVerify")
public ResultSet successVerify(@RequestBody @Valid SuccessVerifyVO levelVO, BindingResult results) {
if (results.hasErrors())
return ResultSet.fail(results.getFieldError().getDefaultMessage());
Task task = service.getOneTaskByTaskId(levelVO.getTaskId());
if (task == null) {
return ResultSet.fail("任务不存在");
}
HashMap<String, Object> map = new HashMap<>();
map.put("handler", levelVO.getUserId());
map.put("userId", levelVO.getNextUserId());
map.put("approve", "yes");
map.put("due", "no");
service.complete(levelVO.getTaskId(), map);
ProcessInstance instance = service.getProcessByProcessId(task.getProcessInstanceId());
if (StringUtils.isNotBlank(levelVO.getVerify())) {
service.setProcessVariable(instance.getId(), "verify", levelVO.getVerify());
}
Task task1 = service.getOneTaskByProcessId(task.getProcessInstanceId());
if (task1 == null) {
return ResultSet.success("流程已完结");
}
ProcessInfo info = new ProcessInfo(task1.getId(), task1.getProcessInstanceId(), instance.getBusinessKey());
return ResultSet.success(info);
}
19
View Source File : ApproveProcessController.java
License : GNU General Public License v3.0
Project Creator : lovelifeming
License : GNU General Public License v3.0
Project Creator : lovelifeming
@ApiOperation("执行同意流程(部门经理)")
@PostMapping("successLevel")
public ResultSet successLevel(@RequestBody @Valid SuccessLevelVO levelVO, BindingResult results) {
if (results.hasErrors())
return ResultSet.fail(results.getFieldError().getDefaultMessage());
Task task = service.getOneTaskByTaskId(levelVO.getTaskId());
if (task == null) {
return ResultSet.fail("任务不存在");
}
HashMap<String, Object> map = new HashMap<>();
map.put("handler", levelVO.getUserId());
map.put("userId", levelVO.getNextUserId());
map.put("approve", "yes");
map.put("level", levelVO.getLevel());
map.put("due", "no");
service.complete(levelVO.getTaskId(), map);
ProcessInstance instance = service.getProcessByProcessId(task.getProcessInstanceId());
service.setProcessVariable(instance.getId(), "level", levelVO.getLevel());
log.info("successLevel成功执行流程,userId={},nextUserId={},level={},processId={},taskId={},businessKey={}", levelVO.getUserId(), levelVO.getNextUserId(), levelVO.getLevel(), instance.getId(), levelVO.getTaskId(), instance.getBusinessKey());
if (StringUtils.isNotBlank(levelVO.getVerify()) && "yes".equals(levelVO.getVerify())) {
service.setProcessVariable(instance.getId(), "verify", levelVO.getVerify());
}
Task task1 = service.getOneTaskByProcessId(task.getProcessInstanceId());
if (task1 == null) {
return ResultSet.success("流程已完结");
}
ProcessInfo info = new ProcessInfo(task1.getId(), task1.getProcessInstanceId(), instance.getBusinessKey());
return ResultSet.success(info);
}
19
View Source File : UserController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@ApiOperation(value = "修改", notes = "修改", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@PostMapping("/update")
public Result update(@Valid @RequestBody User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return userService.update(user);
}
19
View Source File : UserController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@ApiOperation(value = "新增", notes = "新增", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@PostMapping("/save")
public Result save(@Valid @RequestBody User user, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
user.setRegisterIp(getIpAddr());
return userService.insert(user);
}
19
View Source File : RoleController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@ApiOperation(value = "新增", notes = "新增", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@PostMapping("/save")
public Result save(@Valid @RequestBody Role role, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return roleService.insert(role);
}
19
View Source File : RoleController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@ApiOperation(value = "修改", notes = "修改", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@PostMapping("/update")
public Result update(@Valid @RequestBody Role role, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return roleService.update(role);
}
19
View Source File : PermissionController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@Log(description = "修改权限")
@ApiOperation(value = "修改", notes = "修改", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@PostMapping("/update")
public Result update(@Valid @RequestBody Permission permission, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return permissionService.update(permission);
}
19
View Source File : GoodsCategoryController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@ApiOperation(value = "新增", notes = "新增", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@PostMapping("/save")
public Result save(@Valid @RequestBody GoodsCategory goodsCategory, BindingResult bindingResult) {
// 如果验证不通过
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return goodsCategoryService.insert(goodsCategory);
}
19
View Source File : GoodsCategoryController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@ApiOperation(value = "修改", notes = "修改")
@ResponseBody
@PostMapping("/update")
public Result update(@Valid @RequestBody GoodsCategory goodsCategory, BindingResult bindingResult) {
// 如果验证不通过
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return goodsCategoryService.update(goodsCategory);
}
19
View Source File : GenericBaseController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
/**
* 新增
* @param enreplacedy
* @param bindingResult 校验结果
* @return
*/
@ApiOperation(value = "新增", notes = "新增", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@PostMapping("/save")
public Result save(@Valid @RequestBody E enreplacedy, BindingResult bindingResult) {
// 如果验证不通过
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
beforeSave(enreplacedy);
Result result = service.insert(enreplacedy);
afterSave(result);
return result;
}
19
View Source File : GenericBaseController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
/**
* 修改
* @param enreplacedy
* @param bindingResult
* @return
*/
@ApiOperation(value = "修改", notes = "修改")
@ResponseBody
@PostMapping("/update")
public Result update(@Valid @RequestBody E enreplacedy, BindingResult bindingResult) {
// 如果验证不通过
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
beforeUpdate(enreplacedy);
Result result = service.update(enreplacedy);
afterUpdate(result);
return result;
}
19
View Source File : UserController.java
License : MIT License
Project Creator : linj6
License : MIT License
Project Creator : linj6
@PostMapping("/updateUser")
public Result<Integer> updateUser(@Valid UpdateUserVO updateUser, BindingResult bindingResult) {
log.info("请求参数: {}", updateUser);
if (bindingResult.hasErrors()) {
return ResultUtil.error(ResultEnum.PARAM_ERROR.getCode(), bindingResult.getFieldError().getDefaultMessage());
}
return ResultUtil.success(UserDataFacotry.updateUser(User.builder().userId(updateUser.getUserId()).username(updateUser.getUsername()).build()));
}
19
View Source File : PortletRequestDataBinderTests.java
License : Apache License 2.0
Project Creator : liferay
License : Apache License 2.0
Project Creator : liferay
@Test
public void bindingMismatch() {
bean.setAge(30);
request.addParameter("age", "zzz");
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.bind(request);
BindingResult error = binder.getBindingResult();
replacedertNotNull(error.getFieldError("age"));
replacedertEquals("typeMismatch", error.getFieldError("age").getCode());
replacedertEquals(30, bean.getAge());
}
19
View Source File : PortletRequestDataBinderTests.java
License : Apache License 2.0
Project Creator : liferay
License : Apache License 2.0
Project Creator : liferay
@Test
public void bindingFailsWhenMissingRequiredParam() {
PortletRequestDataBinder binder = new PortletRequestDataBinder(bean);
binder.setRequiredFields(new String[] { "age", "name" });
request.addParameter("age", "35");
binder.bind(request);
BindingResult error = binder.getBindingResult();
replacedertNotNull(error.getFieldError("name"));
replacedertEquals("required", error.getFieldError("name").getCode());
}
19
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseNoFieldsSet() throws Exception {
when(projectService.getById(projectId)).thenReturn(project);
when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation));
when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource);
when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
when(projectService.getOrganisationIdFromUser(projectId, loggedInUser)).thenReturn(organisationId);
MvcResult result = mockMvc.perform(post("/project/123/finance-checks/1/new-response").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", "")).andExpect(view().name("project/finance-checks")).andReturn();
FinanceChecksQueryResponseForm form = (FinanceChecksQueryResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals("", form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot be left blank.", bindingResult.getFieldError("response").getDefaultMessage());
}
19
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseTooManyWords() throws Exception {
String tooManyWords = StringUtils.leftPad("a ", 802, "a ");
when(projectService.getById(projectId)).thenReturn(project);
when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation));
when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource);
when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
when(projectService.getOrganisationIdFromUser(projectId, loggedInUser)).thenReturn(organisationId);
MvcResult result = mockMvc.perform(post("/project/123/finance-checks/1/new-response").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooManyWords)).andExpect(view().name("project/finance-checks")).andReturn();
FinanceChecksQueryResponseForm form = (FinanceChecksQueryResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooManyWords, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("Maximum word count exceeded. Please reduce your word count to {1}.", bindingResult.getFieldError("response").getDefaultMessage());
}
19
View Source File : ProjectFinanceChecksControllerQueriesTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
when(projectService.getById(projectId)).thenReturn(project);
when(organisationRestService.getOrganisationById(organisationId)).thenReturn(restSuccess(partnerOrganisation));
when(statusService.getProjectTeamStatus(projectId, Optional.empty())).thenReturn(expectedProjectTeamStatusResource);
when(projectFinanceService.getProjectFinance(projectId, organisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
when(projectService.getOrganisationIdFromUser(projectId, loggedInUser)).thenReturn(organisationId);
MvcResult result = mockMvc.perform(post("/project/123/finance-checks/1/new-response").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooLong)).andExpect(view().name("project/finance-checks")).andReturn();
FinanceChecksQueryResponseForm form = (FinanceChecksQueryResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("response").getDefaultMessage());
}
19
View Source File : BankDetailsControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSubmitBankDetailsWhenInvalidSortCode() throws Exception {
ProjectResource projectResource = setUpMockingForSubmitBankDetails();
MvcResult result = mockMvc.perform(post("/project/{id}/bank-details", projectResource.getId()).contentType(MediaType.APPLICATION_FORM_URLENCODED).param("sortCode", "q234WE").param("accountNumber", "12345678").param("addressForm.addressType", AddressForm.AddressType.MANUAL_ENTRY.name()).param("addressForm.manualAddress.addressLine1", "Montrose House 1").param("addressForm.manualAddress.town", "Neston").param("addressForm.manualAddress.postcode", "CH64 3RU")).andExpect(view().name("project/bank-details")).andExpect(model().hasErrors()).andExpect(model().errorCount(1)).andExpect(model().attributeExists("readOnlyView")).andExpect(model().attribute("readOnlyView", false)).andExpect(model().attributeHasFieldErrors(FORM_ATTR_NAME, "sortCode")).andReturn();
verify(bankDetailsRestService, never()).submitBankDetails(any(), any());
BindingResult bindingResult = ((BankDetailsForm) result.getModelAndView().getModel().get(FORM_ATTR_NAME)).getBindingResult();
replacedertEquals("Please enter a valid sort code.", bindingResult.getFieldError("sortCode").getDefaultMessage());
}
19
View Source File : BankDetailsControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSubmitBankDetailsWhenInvalidAccountDetails() throws Exception {
ProjectResource projectResource = setUpMockingForSubmitBankDetails();
MvcResult result = mockMvc.perform(post("/project/{id}/bank-details", projectResource.getId()).contentType(MediaType.APPLICATION_FORM_URLENCODED).param("sortCode", "1234WE").param("accountNumber", "123tt678").param("addressForm.addressType", AddressForm.AddressType.MANUAL_ENTRY.name()).param("addressForm.manualAddress.addressLine1", "Montrose House 1").param("addressForm.manualAddress.town", "Neston").param("addressForm.manualAddress.postcode", "CH64 3RU")).andExpect(view().name("project/bank-details")).andExpect(model().hasErrors()).andExpect(model().errorCount(2)).andExpect(model().attributeHasFieldErrors(FORM_ATTR_NAME, "accountNumber")).andExpect(model().attributeHasFieldErrors(FORM_ATTR_NAME, "sortCode")).andExpect(model().attributeExists("readOnlyView")).andExpect(model().attribute("readOnlyView", false)).andReturn();
verify(bankDetailsRestService, never()).submitBankDetails(any(), any());
BindingResult bindingResult = ((BankDetailsForm) result.getModelAndView().getModel().get(FORM_ATTR_NAME)).getBindingResult();
replacedertEquals("Please enter a valid account number.", bindingResult.getFieldError("accountNumber").getDefaultMessage());
replacedertEquals("Please enter a valid sort code.", bindingResult.getFieldError("sortCode").getDefaultMessage());
}
19
View Source File : FinanceChecksQueriesControllerTest.java
License : MIT License
Project Creator : InnovateUKGitHub
License : MIT License
Project Creator : InnovateUKGitHub
@Test
public void testSaveNewResponseFieldsTooLong() throws Exception {
String tooLong = StringUtils.leftPad("a", 4001, 'a');
ProjectFinanceResource projectFinanceResource = newProjectFinanceResource().withProject(projectId).withOrganisation(applicantOrganisationId).withId(projectFinanceId).build();
when(projectFinanceService.getProjectFinance(projectId, applicantOrganisationId)).thenReturn(projectFinanceResource);
when(financeCheckServiceMock.getQueries(projectFinanceId)).thenReturn(ServiceResult.serviceSuccess(queries));
MvcResult result = mockMvc.perform(post("/project/" + projectId + "/finance-check/organisation/" + applicantOrganisationId + "/query/" + queryId + "/new-response?query_section=Eligibility").contentType(MediaType.APPLICATION_FORM_URLENCODED).param("response", tooLong)).andExpect(view().name("project/financecheck/queries")).andReturn();
FinanceChecksQueriesAddResponseForm form = (FinanceChecksQueriesAddResponseForm) result.getModelAndView().getModel().get("form");
replacedertEquals(tooLong, form.getResponse());
replacedertEquals(null, form.getAttachment());
BindingResult bindingResult = form.getBindingResult();
replacedertTrue(bindingResult.hasErrors());
replacedertEquals(0, bindingResult.getGlobalErrorCount());
replacedertEquals(1, bindingResult.getFieldErrorCount());
replacedertTrue(bindingResult.hasFieldErrors("response"));
replacedertEquals("This field cannot contain more than {1} characters.", bindingResult.getFieldError("response").getDefaultMessage());
}
See More Examples