當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。