当前位置: 首页>>代码示例>>Java>>正文


Java BindingResult类代码示例

本文整理汇总了Java中org.springframework.validation.BindingResult的典型用法代码示例。如果您正苦于以下问题:Java BindingResult类的具体用法?Java BindingResult怎么用?Java BindingResult使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


BindingResult类属于org.springframework.validation包,在下文中一共展示了BindingResult类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: saveMedic

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@PostMapping
public ResponseEntity<?> saveMedic(@RequestBody Medic medic, BindingResult result) {
	medicValidator.validate(medic, result);

	if (result.hasErrors()) {
		return new ResponseEntity<>(result.getAllErrors(), HttpStatus.NOT_ACCEPTABLE);
	}
	
	Medic newMedic = medicService.save(medic);

	if (newMedic != null) {
		final URI location = ServletUriComponentsBuilder.fromCurrentServletMapping().path("/v1/medics/{id}").build()
				.expand(newMedic.getId()).toUri();

		final HttpHeaders headers = new HttpHeaders();
		headers.setLocation(location);

		return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
	}

	return new ResponseEntity<Void>(HttpStatus.SERVICE_UNAVAILABLE);
}
 
开发者ID:JUGIstanbul,项目名称:second-opinion-api,代码行数:23,代码来源:MedicController.java

示例2: createEvent

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@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";
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:25,代码来源:EventsController.java

示例3: createEvent

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@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";
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:26,代码来源:EventsController.java

示例4: processValidationError

import org.springframework.validation.BindingResult; //导入依赖的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;
}
 
开发者ID:oktadeveloper,项目名称:jhipster-microservices-example,代码行数:13,代码来源:ExceptionTranslator.java

示例5: handleMethodArgumentNotValid

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@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", ErrorConstants.ERR_VALIDATION)
        .with("fieldErrors", fieldErrors)
        .build();
    return create(ex, problem, request);
}
 
开发者ID:torgcrm,项目名称:TorgCRM-Server,代码行数:17,代码来源:ExceptionTranslator.java

示例6: signup

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@RequestMapping(value="/signup/new", method=RequestMethod.POST)
public String signup(final @Valid SignupForm signupForm,
                     final BindingResult result,
                     final 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());

    redirectAttributes.addFlashAttribute("message", "TODO we will implement signup later in the chapter");
    return redirect.apply("/") ;
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:24,代码来源:SignupController.java

示例7: modificar

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@RequestMapping(value = "/modificar", method = RequestMethod.POST)
public String modificar(@ModelAttribute("usuarioAModificar") Usuario usuario, BindingResult bindingResult, Model model) {
    userValidator.validate(usuario, bindingResult);

    if (bindingResult.hasErrors()) {
        return "perfil-usuario";
    }

    Usuario original = FactoriaSA.getInstance().crearSAUsuarios().buscarUsuarioByID(usuario.getId());
    original.setDireccion(usuario.getDireccion());
    original.setLocalidad(usuario.getLocalidad());
    original.setProvincia(usuario.getProvincia());
    original.setCodigoPostal(usuario.getCodigoPostal());
    original.setTelefono(usuario.getTelefono());
    FactoriaComandos.getInstance().crearComando(MODIFICAR_USUARIO).execute(original);

    return "perfil-usuario";
}
 
开发者ID:EventSoftGroup,项目名称:EventSoft,代码行数:19,代码来源:UserController.java

示例8: addFieldError

import org.springframework.validation.BindingResult; //导入依赖的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);
}
 
开发者ID:eduyayo,项目名称:gamesboard,代码行数:21,代码来源:RegistrationController.java

示例9: verifyEditMockRegisteredService

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@Test
public void verifyEditMockRegisteredService() throws Exception {
    registeredServiceFactory.setRegisteredServiceMapper(new MockRegisteredServiceMapper());

    final MockRegisteredService r = new MockRegisteredService();
    r.setId(1000);
    r.setName("Test Service");
    r.setServiceId("test");
    r.setDescription("description");

    this.manager.save(r);
    
    r.setServiceId("serviceId1");
    final RegisteredServiceEditBean.ServiceData data = registeredServiceFactory.createServiceData(r);
    this.controller.saveService(new MockHttpServletRequest(),
            new MockHttpServletResponse(),
            data, mock(BindingResult.class));

    assertFalse(this.manager.getAllServices().isEmpty());
    final RegisteredService r2 = this.manager.findServiceBy(1000);

    assertEquals("serviceId1", r2.getServiceId());
    assertTrue(r2 instanceof MockRegisteredService);
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:25,代码来源:RegisteredServiceSimpleFormControllerTests.java

示例10: verifyAddRegisteredServiceWithValues

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@Test
public void verifyAddRegisteredServiceWithValues() throws Exception {
    final RegisteredServiceImpl svc = new RegisteredServiceImpl();
    svc.setDescription("description");
    svc.setServiceId("serviceId");
    svc.setName("name");
    svc.setEvaluationOrder(123);
    
    assertTrue(this.manager.getAllServices().isEmpty());
    final RegisteredServiceEditBean data = RegisteredServiceEditBean.fromRegisteredService(svc);
    this.controller.saveService(new MockHttpServletRequest(),
            new MockHttpServletResponse(),
            data.getServiceData(), mock(BindingResult.class));

    final Collection<RegisteredService> services = this.manager.getAllServices();
    assertEquals(1, services.size());
    for(final RegisteredService rs : this.manager.getAllServices()) {
        assertTrue(rs instanceof RegexRegisteredService);
    }
}
 
开发者ID:hsj-xiaokang,项目名称:springboot-shiro-cas-mybatis,代码行数:21,代码来源:RegisteredServiceSimpleFormControllerTests.java

示例11: filterModel

import org.springframework.validation.BindingResult; //导入依赖的package包/类
protected Object filterModel(Map<String, Object> model) {
    Iterator it;
    Map<String, Object> result = new HashMap(model.size());
    Set<String> renderedAttributes = !CollectionUtils.isEmpty(this.renderedAttributes) ? this.renderedAttributes : model.keySet();
    for (Entry<String, Object> entry : model.entrySet()) {
        if (!(entry.getValue() instanceof BindingResult) && renderedAttributes.contains(entry.getKey())) {
            result.put(entry.getKey(), entry.getValue());
        }
    }
    if (!this.extractValueFromSingleKeyModel || result.size() != 1) {
        return result;
    }
    it = result.entrySet().iterator();
    if (it.hasNext()) {
        return ((Entry) it.next()).getValue();
    }
    return result;
}
 
开发者ID:JackChan1999,项目名称:boohee_v5.6,代码行数:19,代码来源:FastJsonJsonView.java

示例12: saveService

import org.springframework.validation.BindingResult; //导入依赖的package包/类
/**
 * Adds the service to the Service Registry.
 *
 * @param request  the request
 * @param response the response
 * @param result   the result
 * @param service  the edit bean
 */
@PostMapping(value = "saveService.html")
public void saveService(final HttpServletRequest request, final HttpServletResponse response,
                        @RequestBody final RegisteredServiceEditBean.ServiceData service,
                        final BindingResult result) {
    try {
        final RegisteredService svcToUse = this.registeredServiceFactory.createRegisteredService(service);
        final RegisteredService newSvc = this.servicesManager.save(svcToUse);
        LOGGER.info("Saved changes to service [{}]", svcToUse.getId());

        final Map<String, Object> model = new HashMap<>();
        model.put("id", newSvc.getId());
        model.put("status", HttpServletResponse.SC_OK);
        JsonUtils.render(model, response);
    } catch (final Exception e) {
        throw Throwables.propagate(e);
    }
}
 
开发者ID:mrluo735,项目名称:cas-5.1.0,代码行数:26,代码来源:RegisteredServiceSimpleFormController.java

示例13: singleFileUpload

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@RequestMapping(value="/user/{ssoId}/upload", method = RequestMethod.POST, consumes = "multipart/form-data")
public String singleFileUpload(@Valid FileUpload fileUpload, BindingResult br, Model model, @PathVariable String ssoId, @RequestParam("source") String source, RedirectAttributes attr) throws IOException {
    if(!userService.getPrincipal().equalsIgnoreCase(ssoId)){
        return "redirect:/error";
    }
    if (br.hasErrors()) {
        attr.addFlashAttribute("uploadError", "Please upload a PNG or JPEG formatted file less than 1024 KB.");
        return "redirect:/user/"+ssoId+"?uploadError";
    }

    String SAVE_LOCATION;
    if(source.equalsIgnoreCase("bg")){
        SAVE_LOCATION = servletContext.getRealPath("/resources/") + "pic/bg/" + ssoId + ".jpg";
    }else if(source.equalsIgnoreCase("pp")){
        SAVE_LOCATION = servletContext.getRealPath("/resources/") + "pic/" + ssoId + ".jpg";
    }else {
        attr.addFlashAttribute("uploadError", "Unsupported URL. Please refresh the page and try again.");
        return "redirect:/user/"+ssoId+"?uploadError";
    }

    imageService.saveImage(fileUpload.getFile(),SAVE_LOCATION);

    return "redirect:/user/"+ssoId+"?successup";

}
 
开发者ID:Exercon,项目名称:AntiSocial-Platform,代码行数:26,代码来源:FileUploadController.java

示例14: saveService

import org.springframework.validation.BindingResult; //导入依赖的package包/类
/**
 * Adds the service to the Service Registry.
 * @param request the request
 * @param response the response
 * @param result the result
 * @param service the edit bean
 */
@RequestMapping(method = RequestMethod.POST, value = {"saveService.html"})
public void saveService(final HttpServletRequest request,
                        final HttpServletResponse response,
                        @RequestBody final RegisteredServiceEditBean.ServiceData service,
                        final BindingResult result) {
    try {

        final RegisteredService svcToUse = registeredServiceFactory.createRegisteredService(service);
        final RegisteredService newSvc = this.servicesManager.save(svcToUse);
        logger.info("Saved changes to service {}", svcToUse.getId());

        final Map<String, Object> model = new HashMap<>();
        model.put("id", newSvc.getId());
        model.put("status", HttpServletResponse.SC_OK);
        JsonViewUtils.render(model, response);

    } catch (final Exception e) {
        throw new RuntimeException(e);
    }
}
 
开发者ID:yuweijun,项目名称:cas-server-4.2.1,代码行数:28,代码来源:RegisteredServiceSimpleFormController.java

示例15: signup

import org.springframework.validation.BindingResult; //导入依赖的package包/类
@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());

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

    redirectAttributes.addFlashAttribute("message", "You have successfully signed up and logged in.");
    return "redirect:/";
}
 
开发者ID:PacktPublishing,项目名称:Spring-Security-Third-Edition,代码行数:26,代码来源:SignupController.java


注:本文中的org.springframework.validation.BindingResult类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。