@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); }
@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"; }
@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; }
@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); }
@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("/") ; }
@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"; }
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); }
@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); }
@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); } }
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; }
/** * 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); } }
@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"; }
/** * 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); } }
@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:/"; }
/** * 提交修改编辑用户信息并处理 * * @param id * @return */ @RequestMapping(value = "/edit/{id}", method = RequestMethod.POST) public String edit(@PathVariable String id, final UserInfo userInfo, final BindingResult bindingResult, final RedirectAttributes redirectAttributes) { //校验未通过,返回当前页面重填 if (bindingResult.hasErrors()) { return "/user.html/edit"; } //处理业务逻辑 Result<UserInfo> result = userInfoService.save(userInfo); redirectAttributes.addFlashAttribute("result", result); System.out.println("result = " + result); return "redirect:/user.html/list"; }
@RequestMapping(value = "/login", method = RequestMethod.POST) public String login(@Valid LoginAO loginForm, BindingResult result) { if (result.hasErrors()) { return "login"; } UsernamePasswordToken token = new UsernamePasswordToken(loginForm.getUserName(), loginForm.getPassword()); Subject subject = SecurityUtils.getSubject(); subject.login(token); if (subject.isAuthenticated()) { //登录成功,数据初始化 //1,session信息,用户名,上次登录时间信息 //2,菜单列表信息 //3,系统该要信息,待办事项 return "redirect:/index"; } else { token.clear(); return "login"; } }
@RequestMapping(value = "/add/link", params = {"isLink"}, method = GET) public String addLink(@RequestParam(value = "isLink") Boolean isLink, @Valid PostLink postLink, BindingResult result, Model model, HttpServletRequest request) { model.addAttribute("postheader", webUI.getMessage(ADD_LINK_HEADER)); if (StringUtils.isEmpty(postLink.getLink())) { result.rejectValue("link", "post.link.is.empty"); } else { PagePreviewDTO pagePreview = jsoupService.getPagePreview(postLink.getLink()); if (pagePreview == null) { result.rejectValue("link", "post.link.page.not.found"); return ADMIN_LINK_ADD_VIEW; } else { model.addAttribute("categories", postService.getAdminSelectionCategories()); model.addAttribute("hasLink", true); model.addAttribute("hasCarousel", true); WebUtils.setSessionAttribute(request, "pagePreview", pagePreview); model.addAttribute("pagePreview", pagePreview); model.addAttribute("postDTO", postDtoFromPagePreview(pagePreview, postLink.getLink())); } } return ADMIN_LINK_ADD_VIEW; }
@RequestMapping("/addBook.htm") public ModelAndView addBook(@Valid @ModelAttribute("book") Book book, BindingResult bindingResult) throws Exception { // validator.validate(book, bindingResult); if (bindingResult.hasErrors()) { System.out.println(bindingResult.getAllErrors()); return new ModelAndView("bookForm"); } ModelAndView modelAndView = new ModelAndView(); modelAndView.setViewName("display"); // later on the list will be fetched from the table List<Book> books = new ArrayList(); if (bookService.addBook(book)) { System.out.println("book added"); books.add(book); } modelAndView.addObject("book_list", books); modelAndView.addObject("auth_name", book.getAuthor()); return modelAndView; }
@RequestMapping(method = RequestMethod.PUT) @ResponseBody public String update(@Validated TaskDefineEntity taskDefineEntity, BindingResult bindingResult, HttpServletResponse response, HttpServletRequest request) { if (bindingResult.hasErrors()) { for (ObjectError m : bindingResult.getAllErrors()) { response.setStatus(421); return Hret.error(421, m.getDefaultMessage(), null); } } RetMsg retMsg = taskDefineService.update(parse(request)); if (!retMsg.checkCode()) { response.setStatus(retMsg.getCode()); return Hret.error(retMsg); } return Hret.success(retMsg); }
@RequestMapping(value = "/register", method = RequestMethod.POST) public String register(@Valid @ModelAttribute("userDTO") UserDTO userDTO, BindingResult br, Model model, RedirectAttributes attr, HttpServletRequest request){ if(br.hasErrors()){ attr.addFlashAttribute("userDTO", userDTO); attr.addFlashAttribute("errorBr", br.getAllErrors()); return "redirect:login?registerError"; } User user = new User(userDTO.getSsoId(),userDTO.getEmail(), passwordEncoder.encode(userDTO.getPassword()), userDTO.getName(), State.REGISTER.getName()); UserDetail userDetail = new UserDetail("USER", userDTO.getUserBio()); user.setUserDetail(userDetail); try { userService.saveUser(user); userService.uploadStarterFiles(userDTO.getSsoId()); String appUrl = request.getRequestURL().toString(); eventPublisher.publishEvent(new OnRegistrationCompleteEvent(user, request.getLocale(), appUrl)); }catch(Exception ex){ ex.printStackTrace(); attr.addFlashAttribute("userDTO", userDTO); attr.addFlashAttribute("errorSv", "An error occurred. Please try again."); return "redirect:login?registerError"; } return "redirect:login?success"; }
/** * @desc 分页获取链路数据 * * @author liuliang * * @param request * @param response * @return ComponentResult<Pager<LinkBO>> */ @RequestMapping(value = "/list") @ResponseBody public ComponentResult<Pager<LinkBO>> list(@Validated PageRequestBO pr,BindingResult br) { ComponentResult<Pager<LinkBO>> componentResult = new ComponentResult<Pager<LinkBO>>(); //参数校验 Result validateResult = ValidatorUtil.getValidResult(br); if(ResultUtil.isfail(validateResult)) { return ResultUtil.copy(validateResult, componentResult); } //查询 try { int totalCount = linkService.getLinkCount(pr.getFilterCondition()); List<LinkBO> records = linkService.getLinkList(pr.getFilterCondition(),pr.getPageIndex(),pr.getPageSize()); componentResult.setData(new Pager<LinkBO>(totalCount, records)); return ResultUtil.success(componentResult); } catch (Exception e) { logger.error("分页获取数据异常,params:{}",pr.toString(),e); } //失败返回 return ResultUtil.fail(ErrorCode.QUERY_DB_ERROR,componentResult); }