本文整理汇总了Java中org.springframework.validation.FieldError类的典型用法代码示例。如果您正苦于以下问题:Java FieldError类的具体用法?Java FieldError怎么用?Java FieldError使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
FieldError类属于org.springframework.validation包,在下文中一共展示了FieldError类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: processValidationError
import org.springframework.validation.FieldError; //导入依赖的package包/类
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorVM processValidationError(MethodArgumentNotValidException ex) {
BindingResult result = ex.getBindingResult();
List<FieldError> fieldErrors = result.getFieldErrors();
ErrorVM dto = new ErrorVM(ErrorConstants.ERR_VALIDATION);
for (FieldError fieldError : fieldErrors) {
dto.add(fieldError.getObjectName(), fieldError.getField(), fieldError.getCode());
}
return dto;
}
示例2: processHandler
import org.springframework.validation.FieldError; //导入依赖的package包/类
/**
* Rest handler for validation errors.
* @param ex handled exception
* @return rest result
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex.getBindingResult();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream()
.map(FieldErrorDto::new)
.collect(Collectors.toList());
ValidationResultDto validationResultDto = new ValidationResultDto();
validationResultDto.setFieldErrors(fieldErrorDtos);
return ResponseEntity.badRequest().body(validationResultDto);
}
示例3: build
import org.springframework.validation.FieldError; //导入依赖的package包/类
/**
* 只将第一个错误抛出异常
* @param errResult
* @return
*/
public static ValidationException build(BindingResult errResult) {
FieldError fieldError = errResult.getFieldError();
String code = fieldError.getCode();
String field = fieldError.getField();
String message = fieldError.getDefaultMessage();
message = "`" + field + "` " + message;
ErrorCode errorCode = ErrorCodeConfig.PARAM_INVAILD;
switch (code) {
case "NotNull":
errorCode = ErrorCodeConfig.PARAM_NOTFOUND;
break;
case "Length":
errorCode = ErrorCodeConfig.PARAM_INVAILD_LENGTH;
break;
default:
break;
}
return new ValidationException(errorCode, message);
}
示例4: handleMethodArgumentNotValidException
import org.springframework.validation.FieldError; //导入依赖的package包/类
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public XAPIErrorInfo handleMethodArgumentNotValidException(final HttpServletRequest request, MethodArgumentNotValidException e) {
final List<String> errorMessages = new ArrayList<String>();
for (ObjectError oe : e.getBindingResult().getAllErrors()) {
if (oe instanceof FieldError) {
final FieldError fe = (FieldError)oe;
final String msg = String.format(
"Field error in object '%s' on field '%s': rejected value [%s].", fe.getObjectName(), fe.getField(), fe.getRejectedValue());
errorMessages.add(msg);
} else {
errorMessages.add(oe.toString());
}
}
final XAPIErrorInfo result = new XAPIErrorInfo(HttpStatus.BAD_REQUEST, request, errorMessages);
this.logException(e);
this.logError(result);
return result;
}
开发者ID:Apereo-Learning-Analytics-Initiative,项目名称:OpenLRW,代码行数:21,代码来源:XAPIExceptionHandlerAdvice.java
示例5: escapeObjectError
import org.springframework.validation.FieldError; //导入依赖的package包/类
@SuppressWarnings("unchecked")
private <T extends ObjectError> T escapeObjectError(T source) {
if (source == null) {
return null;
}
if (source instanceof FieldError) {
FieldError fieldError = (FieldError) source;
Object value = fieldError.getRejectedValue();
if (value instanceof String) {
value = HtmlUtils.htmlEscape((String) value);
}
return (T) new FieldError(
fieldError.getObjectName(), fieldError.getField(), value,
fieldError.isBindingFailure(), fieldError.getCodes(),
fieldError.getArguments(), HtmlUtils.htmlEscape(fieldError.getDefaultMessage()));
}
else {
return (T) new ObjectError(
source.getObjectName(), source.getCodes(), source.getArguments(),
HtmlUtils.htmlEscape(source.getDefaultMessage()));
}
}
示例6: processHandler
import org.springframework.validation.FieldError; //导入依赖的package包/类
/**
* Rest handler for validation errors.
* @param ex handled exception
* @return rest result
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ResponseEntity<?> processHandler(MethodArgumentNotValidException ex) {
BindingResult bindingResult = ex.getBindingResult();
List<FieldError> fieldErrors = bindingResult.getFieldErrors();
List<FieldErrorDto> fieldErrorDtos = fieldErrors.stream()
.map(FieldErrorDto::new)
.collect(Collectors.toList());
ValidationResultDto validationResultDto = new ValidationResultDto();
validationResultDto.setFieldErrors(fieldErrorDtos);
LOGGER.error("VALIDATION ERROR: " + ex.getMessage());
return ResponseEntity.badRequest().body(validationResultDto);
}
示例7: getMatcher
import org.springframework.validation.FieldError; //导入依赖的package包/类
private BaseMatcher<BindException> getMatcher(String message, String field) {
return new BaseMatcher<BindException>() {
@Override
public void describeTo(Description description) {
}
@Override
public boolean matches(Object item) {
BindException ex = (BindException) ((Exception) item).getCause();
ObjectError error = ex.getAllErrors().get(0);
boolean messageMatches = message.equals(error.getDefaultMessage());
if (field == null) {
return messageMatches;
}
String fieldErrors = ((FieldError) error).getField();
return messageMatches && fieldErrors.equals(field);
}
};
}
开发者ID:spring-projects,项目名称:spring-security-oauth2-boot,代码行数:23,代码来源:ResourceServerPropertiesTests.java
示例8: addList
import org.springframework.validation.FieldError; //导入依赖的package包/类
/**
* adds new shopping list for the current user
*
* @param newList
* ShoppingListDTO with basic information about new list (must
* include list name)
*/
@RequestMapping(value = "/list", method = RequestMethod.POST)
public String addList(Principal principal, @Valid @ModelAttribute("newList") ShoppingListDTO newList, BindingResult binding, RedirectAttributes attr, HttpSession session) {
LOGGER.debug("addList() method of MvcController called for user: {}", principal.getName());
if(!binding.hasErrors())
repositoryService.addShoppingListToUserByName(principal.getName(), newList.getListName());
else {
attr.addFlashAttribute("org.springframework.validation.BindingResult.newList", binding);
attr.addFlashAttribute("newList", newList);
for(FieldError ferr:binding.getFieldErrors()) {
LOGGER.info("addList(): field error: " + ferr.getDefaultMessage());
}
}
return "redirect:/list";
}
示例9: saveUser
import org.springframework.validation.FieldError; //导入依赖的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";
}
示例10: addFieldError
import org.springframework.validation.FieldError; //导入依赖的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);
}
示例11: saveEmp
import org.springframework.validation.FieldError; //导入依赖的package包/类
/**
* 员工保存
* @param employee
* @return
* 1.支持JSR303校验
* 2.导入Hibernate-Validator
*/
@RequestMapping(value="emp",method=RequestMethod.POST) //定义为POST请求
@ResponseBody
public Msg saveEmp(@Valid Employee employee,BindingResult result){
if(result.hasErrors()){
Map<String,Object> map= new HashMap<>();
//校验失败,应该返回失败,在模态框中显示校验失败的信息
List<FieldError> errors = result.getFieldErrors(); //提取出错误信息
for(FieldError fieldError : errors){
System.out.println("错误的字段名:"+ fieldError.getField());
System.out.println("错误信息:"+fieldError.getDefaultMessage());
map.put(fieldError.getField(), fieldError.getDefaultMessage());
}
return Msg.fail().add("errorFields", map);
}else{
employeeService.saveEmp(employee);
return Msg.success();
}
}
示例12: saveUser
import org.springframework.validation.FieldError; //导入依赖的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";
}
示例13: saveUserAccount
import org.springframework.validation.FieldError; //导入依赖的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";
}
示例14: addEntry
import org.springframework.validation.FieldError; //导入依赖的package包/类
@RequestMapping(value = "/addEntry", method = RequestMethod.POST)
public String addEntry(@Valid @ModelAttribute EntryModel newEntryModel, BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
String errorMessage = "";
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMessage += fieldError.getField() + " is invalid<br>";
}
model.addAttribute("errorMessage", errorMessage);
return "forward:/entry";
}
//if (newEntryModel != null) {
//model.addAttribute("errorMessage", "Entry already exists!<br>");
//} else {
newEntryModel.setDate(new Timestamp(System.currentTimeMillis()));
UserModel user = null;
Authentication auth = SecurityContextHolder.getContext().getAuthentication();
List<UserModel> userList = userRepository.findByUsername(auth.getName());
user = userList.get(0);
newEntryModel.setUser(user);
newEntryModel.setSubforum(null);
entryRepository.save(newEntryModel);
return "forum/entry";
}
示例15: addTopic
import org.springframework.validation.FieldError; //导入依赖的package包/类
@RequestMapping(value = "/addTopic", method = RequestMethod.POST)
public String addTopic(@Valid @ModelAttribute ForumModel newForumModel, BindingResult bindingResult,
Model model) {
if (bindingResult.hasErrors()) {
String errorMessage = "";
for (FieldError fieldError : bindingResult.getFieldErrors()) {
errorMessage += fieldError.getField() + " is invalid<br>";
}
model.addAttribute("errorMessage", errorMessage);
return "/forum";
}
forumRepository.save(newForumModel);
return "/forum";
}