下面列出了org.springframework.web.bind.annotation.ExceptionHandler#org.springframework.validation.BindingResult 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@RequestMapping(value=TgolKeyStore.HOME_URL, method = RequestMethod.POST)
@Secured({TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY})
protected String submitForm(
@ModelAttribute(TgolKeyStore.CONTRACT_SORT_COMMAND_KEY) ContractSortCommand contractDisplayCommand,
BindingResult result,
Model model,
HttpServletRequest request) {
User user = getCurrentUser();
if (!user.getId().equals(contractDisplayCommand.getUserId())) {
throw new ForbiddenUserException();
}
// The page is displayed with sort option. Form needs to be set up
model.addAttribute(
TgolKeyStore.CONTRACT_LIST_KEY,
ContractSortCommandHelper.prepareContractInfo(
user,
contractDisplayCommand,
displayOptionFieldsBuilderList,
model));
return TgolKeyStore.HOME_VIEW_NAME;
}
@Test
public void renderSimpleMap() throws Exception {
Map<String, Object> model = new HashMap<String, Object>();
model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", "bar");
view.setUpdateContentLength(true);
view.render(model, request, response);
assertEquals("no-store", response.getHeader("Cache-Control"));
assertEquals(MappingJackson2XmlView.DEFAULT_CONTENT_TYPE, response.getContentType());
String jsonResult = response.getContentAsString();
assertTrue(jsonResult.length() > 0);
assertEquals(jsonResult.length(), response.getContentLength());
validateResult();
}
@Test
public void updateModelBindingResult() throws Exception {
String commandName = "attr1";
Object command = new Object();
ModelAndViewContainer container = new ModelAndViewContainer();
container.addAttribute(commandName, command);
WebDataBinder dataBinder = new WebDataBinder(command, commandName);
WebDataBinderFactory binderFactory = mock(WebDataBinderFactory.class);
given(binderFactory.createBinder(this.webRequest, command, commandName)).willReturn(dataBinder);
ModelFactory modelFactory = new ModelFactory(null, binderFactory, this.attributeHandler);
modelFactory.updateModel(this.webRequest, container);
assertEquals(command, container.getModel().get(commandName));
String bindingResultKey = BindingResult.MODEL_KEY_PREFIX + commandName;
assertSame(dataBinder.getBindingResult(), container.getModel().get(bindingResultKey));
assertEquals(2, container.getModel().size());
}
/**
* Assert 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);
assertTrue("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();
assertThat("Field name '" + fieldName + "' of attribute '" + name + "'", code, matcher);
};
}
@RequestMapping(method=RequestMethod.POST)
public RedirectView submitForm(Model model, @Validated @ModelAttribute LoginForm adminLoginForm, BindingResult bindingResult){
model.addAttribute("adminLoginForm", adminLoginForm);
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
if(bindingResult.hasErrors()) {
adminLoginForm = new LoginForm();
redirectView.setUrl("/smp/admin_login.html");
model.addAttribute("adminLoginForm", adminLoginForm);
} else{
Login login = new Login();
login.setUserName(adminLoginForm.getUsername());
login.setPassWord(adminLoginForm.getPassword());
if(loginService.isAdminUser(login)){
redirectView.setUrl("/smp/admin_pending.html");
}else{
adminLoginForm = new LoginForm();
redirectView.setUrl("/smp/admin_login.html");
}
}
return redirectView;
}
@Test
public void withSingleValueAndEditor() throws Exception {
this.bean.setName("Rob Harrop");
this.tag.setPath("name");
this.tag.setValue(" Rob Harrop");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(this.bean, COMMAND_NAME);
bindingResult.getPropertyEditorRegistry().registerCustomEditor(String.class, new StringTrimmerEditor(false));
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + COMMAND_NAME, bindingResult);
int result = this.tag.doStartTag();
assertEquals(Tag.SKIP_BODY, result);
String output = getOutput();
// wrap the output so it is valid XML
output = "<doc>" + output + "</doc>";
SAXReader reader = new SAXReader();
Document document = reader.read(new StringReader(output));
Element checkboxElement = (Element) document.getRootElement().elements().get(0);
assertEquals("input", checkboxElement.getName());
assertEquals("checkbox", checkboxElement.attribute("type").getValue());
assertEquals("name", checkboxElement.attribute("name").getValue());
assertEquals("checked", checkboxElement.attribute("checked").getValue());
assertEquals(" Rob Harrop", checkboxElement.attribute("value").getValue());
}
@Test
public void renderNoModelKeyAndBindingResultFirst() throws Exception {
Object toBeMarshalled = new Object();
String modelKey = "key";
Map<String, Object> model = new LinkedHashMap<>();
model.put(BindingResult.MODEL_KEY_PREFIX + modelKey, new BeanPropertyBindingResult(toBeMarshalled, modelKey));
model.put(modelKey, toBeMarshalled);
MockHttpServletRequest request = new MockHttpServletRequest();
MockHttpServletResponse response = new MockHttpServletResponse();
given(marshallerMock.supports(BeanPropertyBindingResult.class)).willReturn(true);
given(marshallerMock.supports(Object.class)).willReturn(true);
view.render(model, request, response);
assertEquals("Invalid content type", "application/xml", response.getContentType());
assertEquals("Invalid content length", 0, response.getContentLength());
verify(marshallerMock).marshal(eq(toBeMarshalled), isA(StreamResult.class));
}
@RequestMapping(value = "/owners", method = RequestMethod.GET)
public String processFindForm(Owner owner, BindingResult result, Map<String, Object> model) {
// allow parameterless GET request for /owners to return all records
if (owner.getLastName() == null) {
owner.setLastName(""); // empty string signifies broadest possible search
}
// find owners by last name
Collection<Owner> results = this.clinicService.findOwnerByLastName(owner.getLastName());
if (results.size() < 1) {
// no owners found
result.rejectValue("lastName", "notFound", "not found");
return "owners/findOwners";
}
if (results.size() > 1) {
// multiple owners found
model.put("selections", results);
return "owners/ownersList";
} else {
// 1 owner found
owner = results.iterator().next();
return "redirect:/owners/" + owner.getId();
}
}
@Override
public ResponseEntity<Problem> handleMethodArgumentNotValid(MethodArgumentNotValidException ex, @Nonnull NativeWebRequest request) {
BindingResult result = ex.getBindingResult();
List<FieldErrorVM> fieldErrors = result.getFieldErrors().stream()
.map(f -> new FieldErrorVM(f.getObjectName(), f.getField(), f.getCode()))
.collect(Collectors.toList());
Problem problem = Problem.builder()
.withType(ErrorConstants.CONSTRAINT_VIOLATION_TYPE)
.withTitle("Method argument not valid")
.withStatus(defaultConstraintViolationStatus())
.with(MESSAGE_KEY, ErrorConstants.ERR_VALIDATION)
.with(FIELD_ERRORS_KEY, fieldErrors)
.build();
return create(ex, problem, request);
}
/**
* 画图并上传
*
* @param poster
* @return Result
*/
@RequestMapping(method = RequestMethod.POST, path = "/poster")
Result drawAndUpload(@RequestBody @Valid Poster poster, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return new BlankResult("error", Objects.requireNonNull(bindingResult.getFieldError()).getDefaultMessage());
}
try {
// 从 数据中心获取结果,如果有,直接返回
Result result = data.find(poster.key());
if (result != null) {
return result;
}
// 如果没有,则画图并上传后存储到数据中心
result = uploader.upload(poster.draw());
if (result.isSuccessful()) {
data.save(poster.key(), result);
}
return result;
} catch (Exception e) {
e.printStackTrace();
return new BlankResult("error", e.getMessage());
}
}
/**
*
* @param auditResultSortCommand
* @param webresourceId
* @param result
* @param model
* @param request
* @return
*/
@RequestMapping(value = {TgolKeyStore.CONTRACT_VIEW_NAME_REDIRECT, TgolKeyStore.PAGE_RESULT_CONTRACT_URL}, method = RequestMethod.POST)
@Secured({TgolKeyStore.ROLE_USER_KEY, TgolKeyStore.ROLE_ADMIN_KEY})
protected String submitPageResultSorter(
@ModelAttribute(TgolKeyStore.AUDIT_RESULT_SORT_COMMAND_KEY) AuditResultSortCommand auditResultSortCommand,
@RequestParam(TgolKeyStore.WEBRESOURCE_ID_KEY) String webresourceId,
BindingResult result,
Model model,
HttpServletRequest request) {
return dispatchDisplayResultRequest(
auditResultSortCommand.getWebResourceId(),
auditResultSortCommand,
model,
request,
false,
null);
}
@ApiOperation(value = "更新品牌")
@RequestMapping(value = "/brand/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateBrand(@PathVariable("id") Long id, @Validated @RequestBody PmsBrandDto pmsBrandDto,BindingResult result) {
if(result.hasErrors()){
return CommonResult.validateFailed(result.getFieldError().getDefaultMessage());
}
CommonResult commonResult;
int count = demoService.updateBrand(id, pmsBrandDto);
if (count == 1) {
commonResult = CommonResult.success(pmsBrandDto);
LOGGER.debug("updateBrand success:{}", pmsBrandDto);
} else {
commonResult = CommonResult.failed("操作失败");
LOGGER.debug("updateBrand failed:{}", pmsBrandDto);
}
return commonResult;
}
@Test
public void renderSimpleBeanWithJsonView() throws Exception {
Object bean = new TestBeanSimple();
Map<String, Object> model = new HashMap<>();
model.put("bindingResult", mock(BindingResult.class, "binding_result"));
model.put("foo", bean);
model.put(JsonView.class.getName(), MyJacksonView1.class);
view.setUpdateContentLength(true);
view.render(model, request, response);
String content = response.getContentAsString();
assertTrue(content.length() > 0);
assertEquals(content.length(), response.getContentLength());
assertTrue(content.contains("foo"));
assertFalse(content.contains("boo"));
assertFalse(content.contains(JsonView.class.getName()));
}
@Test
public void withListAndEditor() throws Exception {
this.tag.setPath("realCountry");
this.tag.setItems(Country.getCountries());
this.tag.setItemValue("isoCode");
this.tag.setItemLabel("name");
BeanPropertyBindingResult bindingResult = new BeanPropertyBindingResult(getTestBean(), "testBean");
bindingResult.getPropertyAccessor().registerCustomEditor(Country.class, new PropertyEditorSupport() {
@Override
public void setAsText(String text) throws IllegalArgumentException {
setValue(Country.getCountryWithIsoCode(text));
}
@Override
public String getAsText() {
return ((Country) getValue()).getName();
}
});
getPageContext().getRequest().setAttribute(BindingResult.MODEL_KEY_PREFIX + "testBean", bindingResult);
this.tag.doStartTag();
String output = getOutput();
assertTrue(output.startsWith("<select "));
assertTrue(output.endsWith("</select>"));
assertTrue(output.contains("option value=\"AT\" selected=\"selected\">Austria"));
}
@RequestMapping(value = "/admin/widgetdetail/update", method = RequestMethod.POST)
public String updateWidgetDetail(@ModelAttribute(ModelKeys.WIDGET) Widget widget, BindingResult result,
@ModelAttribute(ModelKeys.TOKENCHECK) String sessionToken,
@RequestParam String token,
@RequestParam(required = false) String referringPageId,
ModelMap modelMap,
SessionStatus status) {
checkTokens(sessionToken, token, status);
widgetValidator.validate(widget, result);
if (result.hasErrors()) {
addNavigationMenusToModel(SELECTED_ITEM, (Model) modelMap, referringPageId);
modelMap.addAttribute(ModelKeys.REFERRING_PAGE_ID, referringPageId);
modelMap.addAttribute(ModelKeys.CATEGORIES, categoryService.getAllList());
return ViewNames.ADMIN_WIDGETDETAIL;
}
widgetService.updateWidget(widget);
modelMap.clear();
status.setComplete();
return "redirect:/app/admin/widgets?action=update&referringPageId=" + referringPageId;
}
@PostMapping("/email_templets_update")
@ResponseBody
public DataVo updateEmailTemplets(@Valid Email email, 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 = emailService.updateEmailTempletsById(email);
} catch (Exception e) {
data = DataVo.failure(e.getMessage());
}
return data;
}
@Override
public void addFile(FileBrowserFileRequest request, BindingResult bindingResult) {
String path = request.getPath();
String parentFolder = path.substring(0, path.lastIndexOf("/"));
this.checkResource(parentFolder, "Parent Folder", request.isProtectedFolder());
try {
if (this.getStorageManager().exists(request.getPath(), request.isProtectedFolder())) {
bindingResult.reject(FileBrowserValidator.ERRCODE_RESOURCE_ALREADY_EXIST,
new String[]{request.getPath(), String.valueOf(request.isProtectedFolder())}, "fileBrowser.file.exists");
throw new ValidationConflictException(bindingResult);
}
InputStream is = new ByteArrayInputStream(request.getBase64());
this.getStorageManager().saveFile(path, request.isProtectedFolder(), is);
} catch (ValidationConflictException vge) {
throw vge;
} catch (Throwable t) {
logger.error("error adding file path {} - type {}", path, request.isProtectedFolder());
throw new RestServerError("error adding file", t);
}
}
/**
* 创建广告
*
* @param advertise 广告{@link Advertise}
* @return
*/
@RequestMapping(value = "create")
@Transactional(rollbackFor = Exception.class)
public MessageResult create(@Valid Advertise advertise, BindingResult bindingResult,
@SessionAttribute(SESSION_MEMBER) AuthMember member,
@RequestParam(value = "pay[]") String[] pay, String jyPassword) throws Exception {
MessageResult result = BindingResultUtil.validate(bindingResult);
if (result != null) {
return result;
}
Assert.notEmpty(pay, msService.getMessage("MISSING_PAY"));
Assert.hasText(jyPassword, msService.getMessage("MISSING_JYPASSWORD"));
Member member1 = memberService.findOne(member.getId());
Assert.isTrue(member1.getIdNumber() != null, msService.getMessage("NO_REALNAME"));
// if (allow == 1) {
//allow是1的时候,必须是认证商家才能发布广告
Assert.isTrue(member1.getMemberLevel().equals(MemberLevelEnum.IDENTIFICATION), msService.getMessage("NO_BUSINESS"));
// }
String mbPassword = member1.getJyPassword();
Assert.hasText(mbPassword, msService.getMessage("NO_SET_JYPASSWORD"));
Assert.isTrue(Md5.md5Digest(jyPassword + member1.getSalt()).toLowerCase().equals(mbPassword), msService.getMessage("ERROR_JYPASSWORD"));
AdvertiseType advertiseType = advertise.getAdvertiseType();
StringBuffer payMode = checkPayMode(pay, advertiseType, member1);
advertise.setPayMode(payMode.toString());
OtcCoin otcCoin = otcCoinService.findOne(advertise.getCoin().getId());
checkAmount(advertiseType, advertise, otcCoin, member1);
advertise.setLevel(AdvertiseLevel.ORDINARY);
advertise.setRemainAmount(advertise.getNumber());
Member mb = new Member();
mb.setId(member.getId());
advertise.setMember(mb);
Advertise ad = advertiseService.saveAdvertise(advertise);
if (ad != null) {
return MessageResult.success(msService.getMessage("CREATE_SUCCESS"));
} else {
return MessageResult.error(msService.getMessage("CREATE_FAILED"));
}
}
@PutMapping(value = "/update",produces = "application/json;charset=UTF-8",consumes = "application/json;charset=UTF-8")
@ResponseBody
public ResponseResult updateUserInfo(@Valid @RequestBody UserVo userVo, BindingResult result){
UserVo resultVo = userService.updateUserInfo(userVo,result);
if (null!=resultVo){
return ResponseResult.createBySuccess("用户信息修改成功",userVo);
}
return ResponseResult.createByErrorMessage("用户信息修改失败");
}
private List<String> toList(BindingResult bindingResult) {
List<String> errors = new ArrayList<>();
if(bindingResult.hasErrors()) {
bindingResult.getFieldErrors().forEach(err -> {
errors.add(err.getDefaultMessage());
});
}
return errors;
}
/**
* 查询服务消费方列表
*
* @param body
* @param result
* @return
*/
@RequestMapping(value = "/consumer", method = RequestMethod.GET)
public Response<QueryPagingListResponseBody> consumer(@Validated QueryServiceDiscoveryDetailRequestBody body, BindingResult result) {
if (result.hasErrors()) {
return new Response<>(SystemErrCode.ERRCODE_INVALID_PARAMETER, result.getFieldError().getDefaultMessage());
}
return this.serviceDiscoveryImpl.consumer(body);
}
@ActivityStreamAuditable
@RestAccessControl(permission = Permission.MANAGE_PAGES)
@RequestMapping(value = "/pages/{pageCode}", method = RequestMethod.DELETE, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<?>> deletePage(@ModelAttribute("user") UserDetails user, @PathVariable String pageCode) throws ApsSystemException {
logger.debug("deleting {}", pageCode);
if (!this.getAuthorizationService().isAuth(user, pageCode)) {
return new ResponseEntity<>(new SimpleRestResponse<>(new PageDto()), HttpStatus.UNAUTHORIZED);
}
DataBinder binder = new DataBinder(pageCode);
BindingResult bindingResult = binder.getBindingResult();
//field validations
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
//business validations
getPageValidator().validateOnlinePage(pageCode, bindingResult);
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
//business validations
getPageValidator().validateChildren(pageCode, bindingResult);
if (bindingResult.hasErrors()) {
throw new ValidationGenericException(bindingResult);
}
this.getPageService().removePage(pageCode);
Map<String, String> payload = new HashMap<>();
payload.put("code", pageCode);
return new ResponseEntity<>(new SimpleRestResponse<>(payload), HttpStatus.OK);
}
@RequestMapping("/myPath.do")
public String myHandle(@ModelAttribute("myCommand") TestBean tb, BindingResult errors, ModelMap model) {
FieldError error = errors.getFieldError("age");
assertNotNull("Must have field error for age property", error);
assertEquals("value2", error.getRejectedValue());
if (!model.containsKey("myKey")) {
model.addAttribute("myKey", "myValue");
}
return "myView";
}
@Log(description = "新增权限")
@ApiOperation(value = "新增", notes = "新增", httpMethod = "POST", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@ResponseBody
@PostMapping("/save")
public Result save(@Valid @RequestBody Permission permission, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return Result.error(bindingResult.getFieldError().getDefaultMessage());
}
return permissionService.insert(permission);
}
@ApiOperation(value = "更新诊断目录信息")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody DmsDiseCatalogParam dmsDiseCatalogParam , BindingResult result){
int count = dmsDiseCatalogService.update(id,dmsDiseCatalogParam);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation(value = "更新诊断信息")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody DmsDiseParam dmsDiseParam , BindingResult result){
int count = dmsDiseService.update(id,dmsDiseParam);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
/**
* 增加时需要传入{parentId}
* <p>author:赵煜
*/
@ApiOperation(value = "新增病历模板目录或模板")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody DmsCaseModelOrCatalogParam dmsCaseModelOrCatalogParam, BindingResult result) {
int count = dmsCaseModelService.createCatOrModel(dmsCaseModelOrCatalogParam);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
@ApiOperation(value = "更新")
@RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
@ResponseBody
public CommonResult update(@PathVariable Long id, @RequestBody DmsDiseParam dmsDiseParam , BindingResult result){
int count = dmsDiseService.update(id,dmsDiseParam);
if (count > 0) {
return CommonResult.success(count);
}
return CommonResult.failed();
}
/**
* 自定义校验
* http://localhost:8080/diyValidate?flag1=%22a%20b%22
*/
@RequestMapping("/diyValidate")
@ResponseBody
public String diyValidate(@Validated DiyBean diyBean, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
for (FieldError fieldError : bindingResult.getFieldErrors()) {
//...
}
return "fail";
}
return "success";
}
@RequestMapping(value = "/{ownerId}/edit", method = RequestMethod.POST)
public String processUpdateOwner(@Valid Owner owner, BindingResult result, SessionStatus status) {
if (result.hasErrors()) {
return "owners/ownerForm";
} else {
this.clinicService.saveOwner(owner);
status.setComplete();
return "redirect:/owners/{ownerId}";
}
}