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

The following examples show how to use org.springframework.validation.BindingResult#hasErrors() . 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: GuiFragmentController.java    From entando-core with GNU Lesser General Public License v3.0 8 votes vote down vote up
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/{fragmentCode}", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<SimpleRestResponse<GuiFragmentDto>> updateGuiFragment(@PathVariable String fragmentCode, @Valid @RequestBody GuiFragmentRequestBody guiFragmentRequest, BindingResult bindingResult) {
    //field validations
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    int result = this.getGuiFragmentValidator().validateBody(fragmentCode, guiFragmentRequest, bindingResult);
    if (bindingResult.hasErrors()) {
        if (404 == result) {
            throw new ResourceNotFoundException(GuiFragmentValidator.ERRCODE_FRAGMENT_DOES_NOT_EXISTS, "fragment", fragmentCode);
        } else {
            throw new ValidationGenericException(bindingResult);
        }
    }
    GuiFragmentDto fragment = this.getGuiFragmentService().updateGuiFragment(guiFragmentRequest);
    return new ResponseEntity<>(new SimpleRestResponse<>(fragment), HttpStatus.OK);
}
 
Example 2
Source File: ValidatorController.java    From yuzhouwan with Apache License 2.0 8 votes vote down vote up
@ApiOperation(
        value = "获得商品信息",
        notes = "获取商品信息(用于数据同步)",
        httpMethod = "POST",
        response = String.class,
        produces = MediaType.APPLICATION_JSON_VALUE)
@Produces(MediaType.APPLICATION_JSON_VALUE)
@Consumes(MediaType.APPLICATION_JSON_VALUE)
@ApiResponses(value = {
        @ApiResponse(code = 200, message = "商品信息", response = String.class),
        @ApiResponse(code = 201, message = "ErrorType.errorCheckToken" + "(token验证失败)", response = String.class),
        @ApiResponse(code = 202, message = "ErrorType.error500" + "(系统错误)", response = String.class)})
@RequestMapping(value = "/save", method = RequestMethod.POST)
public String save(@ApiParam(required = true)
                   @Validated({Second.class})
                   /*@RequestBody*/ @ModelAttribute UserModel userModel, BindingResult result) {
    if (result.hasErrors()) {
        return ValidationUtils.getErrorInfos(result);
    }
    return "redirect:/success";
}
 
Example 3
Source File: EventsController.java    From Spring-Security-Third-Edition with MIT License 8 votes vote down vote up
@PostMapping(value = "/new")
public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return "events/create";
    }
    CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail());
    if (attendee == null) {
        result.rejectValue("attendeeEmail", "attendeeEmail.missing",
                "Could not find a user for the provided Attendee Email");
    }
    if (result.hasErrors()) {
        return "events/create";
    }
    Event event = new Event();
    event.setAttendee(attendee);
    event.setDescription(createEventForm.getDescription());
    event.setOwner(userContext.getCurrentUser());
    event.setSummary(createEventForm.getSummary());
    event.setWhen(createEventForm.getWhen());
    calendarService.createEvent(event);
    redirectAttributes.addFlashAttribute("message", "Successfully added the new event");
    return "redirect:/events/my";
}
 
Example 4
Source File: PageController.java    From entando-core with GNU Lesser General Public License v3.0 8 votes vote down vote up
@ActivityStreamAuditable
@RestAccessControl(permission = Permission.SUPERUSER)
@RequestMapping(value = "/pages/{pageCode}/status", method = RequestMethod.PUT, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<RestResponse<PageDto, Map<String, String>>> updatePageStatus(
        @ModelAttribute("user") UserDetails user, @PathVariable String pageCode,
        @Valid @RequestBody PageStatusRequest pageStatusRequest, BindingResult bindingResult) {
    logger.debug("changing status for page {} with request {}", pageCode, pageStatusRequest);
    Map<String, String> metadata = new HashMap<>();
    if (!this.getAuthorizationService().isAuth(user, pageCode)) {
        return new ResponseEntity<>(new RestResponse<>(new PageDto(), metadata), HttpStatus.UNAUTHORIZED);
    }
    //field validations
    if (bindingResult.hasErrors()) {
        throw new ValidationGenericException(bindingResult);
    }
    PageDto page = this.getPageService().updatePageStatus(pageCode, pageStatusRequest.getStatus());
    metadata.put("status", pageStatusRequest.getStatus());
    return new ResponseEntity<>(new RestResponse<>(page, metadata), HttpStatus.OK);
}
 
Example 5
Source File: EmployeeController.java    From ManagementSystem with Apache License 2.0 8 votes vote down vote up
/**
 * 添加员工
 *1. 支持JSR303校验
 *2. 导入hibernate-validator
 *3. bean加入patten注解
 *4. BindingResult来获得错误信息
 * @param employee
 * @return
 */
@RequestMapping("/emp")
@ResponseBody
public Msg addEmp(@Valid Employee employee, BindingResult bindingResult){
    if(bindingResult.hasErrors()) {
        //校验失败返回错误信息
        Map<String ,Object> map = new HashMap<String, Object>();
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        for(FieldError error : fieldErrors){
            System.out.println("错误的字段名"+error.getField());
            System.out.println("错误的信息"+error.getDefaultMessage());
            map.put(error.getField(),error.getDefaultMessage());
        }
        return Msg.fail().add("errorFields",map);
    }else {
        int result = iEmployeeService.addEmp(employee);
        if(result != 0){
            return this.getEmpsWithJson(1);
        }else{
            return Msg.fail().add("errMsg","新增信息失败");
        }
    }
}
 
Example 6
Source File: EventsController.java    From Spring-Security-Third-Edition with MIT License 6 votes vote down vote up
@RequestMapping(value = "/new", method = RequestMethod.POST)
public String createEvent(@Valid CreateEventForm createEventForm, BindingResult result,
        RedirectAttributes redirectAttributes) {
    if (result.hasErrors()) {
        return "events/create";
    }
    CalendarUser attendee = calendarService.findUserByEmail(createEventForm.getAttendeeEmail());
    if (attendee == null) {
        result.rejectValue("attendeeEmail", "attendeeEmail.missing",
                "Could not find a user for the provided Attendee Email");
    }
    if (result.hasErrors()) {
        return "events/create";
    }
    Event event = new Event();
    event.setAttendee(attendee);
    event.setDescription(createEventForm.getDescription());
    event.setOwner(userContext.getCurrentUser());
    event.setSummary(createEventForm.getSummary());
    event.setWhen(createEventForm.getWhen());
    calendarService.createEvent(event);
    redirectAttributes.addFlashAttribute("message", "Successfully added the new event");
    return "redirect:/events/my";
}
 
Example 7
Source File: AdminEmployeeController.java    From SA47 with The Unlicense 6 votes vote down vote up
@RequestMapping(value = "/create", method = RequestMethod.POST)
public ModelAndView createNewEmployee(@ModelAttribute @Valid Employee employee, BindingResult result,
		final RedirectAttributes redirectAttributes) {

	if (result.hasErrors())
		return new ModelAndView("employee-new");

	ModelAndView mav = new ModelAndView();
	String message = "New employee " + employee.getEmployeeId() + " was successfully created.";

	eService.createEmployee(employee);
	mav.setViewName("redirect:/admin/employee/list");

	redirectAttributes.addFlashAttribute("message", message);
	return mav;
}
 
Example 8
Source File: AttendanceUploadController.java    From zhcet-web with Apache License 2.0 6 votes vote down vote up
@PostMapping("/confirm")
public String uploadAttendance(RedirectAttributes attributes, @PathVariable String code, @Valid @ModelAttribute AttendanceModel attendanceModel, BindingResult bindingResult) {
    CourseInCharge courseInCharge = courseInChargeService.getCourseInCharge(code).orElseThrow(CourseInChargeNotFoundException::new);

    if (bindingResult.hasErrors()) {
        attributes.addFlashAttribute("attendanceModel", attendanceModel);
        attributes.addFlashAttribute("org.springframework.validation.BindingResult.attendanceModel", bindingResult);
    } else {
        try {
            attendanceUploadService.updateAttendance(courseInCharge, attendanceModel.getUploadList());
            attributes.addFlashAttribute("updated", true);
        } catch (Exception e) {
            log.error("Attendance Confirm", e);
            attributes.addFlashAttribute("attendanceModel", attendanceModel);
            attributes.addFlashAttribute("unknown_error", true);
        }
    }

    return "redirect:/admin/faculty/courses/{code}/attendance";
}
 
Example 9
Source File: VisitController.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@RequestMapping(value = "/owners/{ownerId}/pets/{petId}/visits/new", method = RequestMethod.POST)
public String processNewVisitForm(@Valid Visit visit, BindingResult result) {
    if (result.hasErrors()) {
        return "pets/createOrUpdateVisitForm";
    } else {
        this.clinicService.saveVisit(visit);
        return "redirect:/owners/{ownerId}";
    }
}
 
Example 10
Source File: UserController.java    From tutorials with MIT License 5 votes vote down vote up
@PostMapping("/update/{id}")
public String updateUser(@PathVariable("id") long id, @Valid User user, BindingResult result, Model model) {
    if (result.hasErrors()) {
        user.setId(id);
        return "update-user";
    }
    
    userRepository.save(user);
    model.addAttribute("users", userRepository.findAll());
    return "redirect:/index";
}
 
Example 11
Source File: RoleHtmlController.java    From spring-boot-doma2-sample with Apache License 2.0 5 votes vote down vote up
/**
 * 検索結果
 *
 * @param form
 * @param br
 * @param attributes
 * @return
 */
@PostMapping("/find")
public String findRole(@Validated @ModelAttribute("searchRoleForm") SearchRoleForm form, BindingResult br,
        RedirectAttributes attributes) {
    // 入力チェックエラーがある場合は、元の画面にもどる
    if (br.hasErrors()) {
        setFlashAttributeErrors(attributes, br);
        return "redirect:/system/roles/find";
    }

    return "redirect:/system/roles/find";
}
 
Example 12
Source File: SignupController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping(value="/signup/new",method=RequestMethod.POST)
public String signup(@Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {
    if(result.hasErrors()) {
        return "signup/form";
    }

    String email = signupForm.getEmail();
    if(calendarService.findUserByEmail(email) != null) {
        result.rejectValue("email", "errors.signup.email", "Email address is already in use.");
        return "signup/form";
    }

    CalendarUser user = new CalendarUser();
    user.setEmail(email);
    user.setFirstName(signupForm.getFirstName());
    user.setLastName(signupForm.getLastName());
    user.setPassword(signupForm.getPassword());

    logger.info("CalendarUser: {}", user);

    int id = calendarService.createUser(user);
    user.setId(id);
    userContext.setCurrentUser(user);

    redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in.");
    return "redirect:/";
}
 
Example 13
Source File: AdminLayoutController.java    From abixen-platform with GNU Lesser General Public License v2.1 5 votes vote down vote up
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
FormValidationResultRepresentation<LayoutForm> update(@PathVariable Long id, @RequestBody @Valid LayoutForm layoutForm, BindingResult bindingResult) {
    log.debug("update() - id: {}, layoutForm: {}", id, layoutForm);

    if (bindingResult.hasErrors()) {
        List<FormErrorRepresentation> formErrors = ValidationUtil.extractFormErrors(bindingResult);
        return new FormValidationResultRepresentation<>(layoutForm, formErrors);
    }

    final LayoutForm updatedLayoutForm = layoutManagementService.updateLayout(layoutForm);

    return new FormValidationResultRepresentation<>(updatedLayoutForm);
}
 
Example 14
Source File: ParentController.java    From es with Apache License 2.0 5 votes vote down vote up
/**
 * 验证失败返回true
 *
 * @param parent
 * @param result
 * @return
 */
protected boolean hasError(Parent parent, BindingResult result) {
    Assert.notNull(parent);

    //全局错误 前台使用<es:showGlobalError commandName="showcase/parent"/> 显示
    if (parent.getName().contains("admin")) {
        result.reject("name.must.not.admin");
    }

    return result.hasErrors();
}
 
Example 15
Source File: ArticleController.java    From NoteBlog with MIT License 5 votes vote down vote up
@PostMapping("/post")
@ResponseBody
public R post(@Valid Article article, String tagName, BindingResult result, @CookieValue(SessionParam.SESSION_ID_COOKIE) String uuid) {
    if (!result.hasErrors()) {
        article.setAuthorId(blogContext.getSessionUser(uuid).getId());
        return builder("发布博文").exec(() -> articleService.postArticle(article, tagName));
    } else {
        return check(rTemplate, result);
    }
}
 
Example 16
Source File: SignupController.java    From Spring-Security-Third-Edition with MIT License 5 votes vote down vote up
@RequestMapping(value="/signup/new",method=RequestMethod.POST)
public String signup(@Valid SignupForm signupForm, BindingResult result, RedirectAttributes redirectAttributes) {
    if(result.hasErrors()) {
        return "signup/form";
    }

    String email = signupForm.getEmail();
    if(calendarService.findUserByEmail(email) != null) {
        result.rejectValue("email", "errors.signup.email", "Email address is already in use.");
        return "signup/form";
    }

    CalendarUser user = new CalendarUser();
    user.setEmail(email);
    user.setFirstName(signupForm.getFirstName());
    user.setLastName(signupForm.getLastName());
    user.setPassword(signupForm.getPassword());

    logger.info("CalendarUser: {}", user);

    int id = calendarService.createUser(user);
    user.setId(id);
    userContext.setCurrentUser(user);

    redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in.");
    return "redirect:/";
}
 
Example 17
Source File: PersonListController.java    From softwarecave with GNU General Public License v3.0 5 votes vote down vote up
@RequestMapping(method = RequestMethod.POST)
public String add(@ModelAttribute(value = "newPerson") Person newPerson, BindingResult result, Model model) {
    if (result.hasErrors())
        return "personlist";
    
    list.addPerson(newPerson);
    return "redirect:/personlist";
}
 
Example 18
Source File: AccountController.java    From Spring5Tutorial with GNU Lesser General Public License v3.0 5 votes vote down vote up
private List<String> toList(BindingResult bindingResult) {
    List<String> errors = new ArrayList<>(); 
    if(bindingResult.hasErrors()) {
        bindingResult.getFieldErrors().forEach(err -> {
            errors.add(err.getDefaultMessage());
        });
    }
    return errors;
}
 
Example 19
Source File: ProjectController.java    From AthenaServing with Apache License 2.0 5 votes vote down vote up
/**
 * 查询项目成员列表
 *
 * @param body
 * @param result
 * @return
 */
@RequestMapping(value = "/member/list", method = RequestMethod.GET)
@Access(authorities = "admin")
public Response<QueryPagingListResponseBody> findMemberList(@Validated QueryProjectMemberRequestBody body, BindingResult result) {
    if (result.hasErrors()) {
        return new Response<>(SystemErrCode.ERRCODE_INVALID_PARAMETER, result.getFieldError().getDefaultMessage());
    }
    return this.projectServiceImpl.findMemberList(body);
}
 
Example 20
Source File: ShowController.java    From es with Apache License 2.0 3 votes vote down vote up
/**
 * 验证失败返回true
 *
 * @param m
 * @param result
 * @return
 */
@Override
protected boolean hasError(Show m, BindingResult result) {
    Assert.notNull(m);

    return result.hasErrors();
}