@Controller
public class MyController {

    @RequestMapping(method = RequestMethod.POST, value = "myPage.html")
    public void myHandler(MyForm myForm, BindingResult result, Model model) {
        result.reject("field1", "error message 1");
    }
}

        

@RequestMapping(value="/confirm", method = RequestMethod.POST)
public ModelAndView processConfirmationForm(ModelAndView modelAndView, BindingResult bindingResult, @RequestParam Map requestParams, RedirectAttributes redir) {

	modelAndView.setViewName("confirm");

	Zxcvbn passwordCheck = new Zxcvbn();

	Strength strength = passwordCheck.measure(requestParams.get("password"));

	if (strength.getScore() < 3) {
		bindingResult.reject("password");

		redir.addFlashAttribute("errorMessage", "Your password is too weak.  Choose a stronger one.");

		modelAndView.setViewName("redirect:confirm?token=" + requestParams.get("token"));
		System.out.println(requestParams.get("token"));
		return modelAndView;
	}

	// Find the user associated with the reset token
	User user = userService.findByConfirmationToken(requestParams.get("token"));

	// Set new password
	user.setPassword(bCryptPasswordEncoder.encode(requestParams.get("password")));

	// Set user to enabled
	user.setEnabled(true);

	// Save user
	userService.saveUser(user);

	modelAndView.addObject("successMessage", "Your password has been set!");
	return modelAndView;		
}

        

@RequestMapping(value = "/register", method = RequestMethod.POST)
public ModelAndView processRegistrationForm(ModelAndView modelAndView, @Valid User user, BindingResult bindingResult, HttpServletRequest request) {

	// Lookup user in database by e-mail
	User userExists = userService.findByEmail(user.getEmail());

	System.out.println(userExists);

	if (userExists != null) {
		modelAndView.addObject("alreadyRegisteredMessage", "Oops!  There is already a user registered with the email provided.");
		modelAndView.setViewName("register");
		bindingResult.reject("email");
	}

	if (bindingResult.hasErrors()) { 
		modelAndView.setViewName("register");		
	} else { // new user so we create user and send confirmation e-mail

		// Disable user until they click on confirmation link in email
		user.setEnabled(false);

		// Generate random 36-character string token for confirmation link
		user.setConfirmationToken(UUID.randomUUID().toString());

		userService.saveUser(user);

		String appUrl = request.getScheme() + "://" + request.getServerName();

		SimpleMailMessage registrationEmail = new SimpleMailMessage();
		registrationEmail.setTo(user.getEmail());
		registrationEmail.setSubject("Registration Confirmation");
		registrationEmail.setText("To confirm your e-mail address, please click the link below:\n"
				+ appUrl + "/confirm?token=" + user.getConfirmationToken());
		registrationEmail.setFrom("noreply@domain.com");

		emailService.sendEmail(registrationEmail);

		modelAndView.addObject("confirmationMessage", "A confirmation e-mail has been sent to " + user.getEmail());
		modelAndView.setViewName("register");
	}

	return modelAndView;
}

        

@PreAuthorize("hasAuthority('ADMIN')")
    @RequestMapping(value = "/user/create", method = RequestMethod.POST)
    public String handleUserCreateForm(@Valid @ModelAttribute("form") UserBean form, BindingResult bindingResult) {
      LOGGER.debug("Processing user create form={}, bindingResult={}", form, bindingResult);
        if (bindingResult.hasErrors()) {
            return "user_create";
        }
        try {
            userService.create(form);
        } catch (DataIntegrityViolationException e) {
         LOGGER.warn("Exception occurred when trying to save the user, assuming duplicate email", e);
            bindingResult.reject("email.exists", "Email already exists");
            return "user_create";
        }
        return "redirect:/users";
    }
}

        

@RequestMapping("/projects/create")
public String create(@Validated ProjectCreateForm projectCreateForm, BindingResult bindingResult) {
	if (bindingResult.hasErrors()) {
		bindingResult.reject("message.error.param", new Object[]{"foo"}, null);
		return "projects/list";
	}
	try {
		projectService.create(projectCreateForm.getName());
	} catch (Exception e) {
		logHandler.handle(e);
	}
	return "projects/list";
}

        

@RequestMapping(value = "/users/password", method = RequestMethod.POST)
public String setPasswordPage(@Valid UserPasswordDTO userPasswordDTO, BindingResult result, Model model,
                              RedirectAttributes attributes) {

    long userId = userPasswordDTO.getUserId();
    if (result.hasErrors()) {
        model.addAttribute("userDescription", getUserDescription(userId));
        return ADMIN_USERPASSWORD_VIEW;
    } else {
        if (!userPasswordDTO.getPassword().equals(userPasswordDTO.getRepeatedPassword())) {
            result.reject(GLOBAL_ERROR_PASSWORDS_DONOT_MATCH_KEY);
            model.addAttribute("userDescription", getUserDescription(userId));
            return ADMIN_USERPASSWORD_VIEW;
        } else {
            userService.updatePassword(userPasswordDTO);
            Optional<User> user = userService.getUserById(userPasswordDTO.getUserId());
            if (user.isPresent()) {
                webUI.addFeedbackMessage(attributes, FEEDBACK_USER_PASSWORD_UPDATED_KEY, user.get().getFirstName(),
                        user.get().getLastName());
            }
        }
    }
    return "redirect:/admin/users";
}

        

private void doValidate() throws BindException {
	BindingResult errors = new BeanPropertyBindingResult(this,
			"resourceServerProperties");
	boolean jwtConfigPresent = StringUtils.hasText(this.jwt.getKeyUri())
			|| StringUtils.hasText(this.jwt.getKeyValue());
	boolean jwkConfigPresent = StringUtils.hasText(this.jwk.getKeySetUri());
	if (jwtConfigPresent && jwkConfigPresent) {
		errors.reject("ambiguous.keyUri",
				"Only one of jwt.keyUri (or jwt.keyValue) and jwk.keySetUri should"
						+ " be configured.");
	}
	if (!jwtConfigPresent && !jwkConfigPresent) {
		if (!StringUtils.hasText(this.userInfoUri)
				&& !StringUtils.hasText(this.tokenInfoUri)) {
			errors.rejectValue("tokenInfoUri", "missing.tokenInfoUri",
					"Missing tokenInfoUri and userInfoUri and there is no "
							+ "JWT verifier key");
		}
		if (StringUtils.hasText(this.tokenInfoUri) && isPreferTokenInfo()) {
			if (!StringUtils.hasText(this.clientSecret)) {
				errors.rejectValue("clientSecret", "missing.clientSecret",
						"Missing client secret");
			}
		}
	}
	if (errors.hasErrors()) {
		throw new BindException(errors);
	}
}

        

@RequestMapping(value = "technician-add", method = RequestMethod.POST)
  public String add(@ModelAttribute("technicianAttribute") TechnicianUserWrapper technicianWrapper, BindingResult result, Model model) {

    if (technicianWrapper.getFirstName() == null || technicianWrapper.getSurname() == null
            || technicianWrapper.getUsername() == null || technicianWrapper.getPassword() == null) {
      result.reject("e", ERR_OMMITEDFIELD);
    } else if (!testUniqueName(technicianWrapper.getUsername())) {
      result.reject("e", ERR_USERNAMEEXISTS);
    }

    if (result.hasErrors()) {
      model.addAttribute("actionURL", "/technician-add");
      return "technician-add";
    }

    Technician technician = new Technician();
    technician.setFirstName(technicianWrapper.getFirstName());
    technician.setSurname(technicianWrapper.getSurname());
    technician.setDateHired(technicianWrapper.getDateHired());
    technician.setDateOfBirth(technicianWrapper.getDateOfBirth());
    technician.setDegree(technicianWrapper.getDegree());

    User user = new User();
    user.setActive(1);
    user.setUsername(technicianWrapper.getUsername());

    user.setPassword(encryptPassword(technicianWrapper.getPassword(), technicianWrapper.getUsername()));
    user.setKindOfUser("ROLE_TECHNIK");

    user.setTechnician(technician);

    userService.addUser(user);

    model.addAttribute("id", user.getTechnician().getId());
    return "redirect:/technician-detail";
  }


        

public String addSpitterFromForm(@Valid JobDesc jobDesc,BindingResult bindingResult){
	if(bindingResult.hasErrors()){
		return"login/hello";
	}
	try{
		jobDesc.setJobName(new String(jobDesc.getJobName().getBytes("iso-8859-1"),"utf-8"));
		jobDesc.setJobGroup(new String(jobDesc.getJobGroup().getBytes("iso-8859-1"),"utf-8"));
		jobDesc.setTrigName(new String(jobDesc.getTrigName().getBytes("iso-8859-1"),"utf-8"));
		jobDesc.setTrigGroup(new String(jobDesc.getTrigGroup().getBytes("iso-8859-1"),"utf-8"));
		jobMgrService.addSche(jobDesc);
	}catch(Exception e){
		bindingResult.reject(e.getMessage());
		return"login/hello";
	}
	return "redirect:/quartz/login?jobName="+jobDesc.getJobName()+"&jobGroup="+jobDesc.getJobGroup();
}

        

private List<SecretFile> handleStream(final HttpServletRequest req,
                                      final KeyIv encryptionKey, final DataBinder binder)
    throws FileUploadException, IOException {

    final BindingResult errors = binder.getBindingResult();

    final MutablePropertyValues propertyValues = new MutablePropertyValues();
    final List<SecretFile> tmpFiles = new ArrayList<>();

    @SuppressWarnings("checkstyle:anoninnerlength")
    final AbstractMultipartVisitor visitor = new AbstractMultipartVisitor() {

        private OptionalInt expiration = OptionalInt.empty();

        @Override
        void emitField(final String name, final String value) {
            propertyValues.addPropertyValue(name, value);

            if ("expirationDays".equals(name)) {
                expiration = OptionalInt.of(Integer.parseInt(value));
            }
        }

        @Override
        void emitFile(final String fileName, final InputStream inStream) {
            final Integer expirationDays = expiration
                .orElseThrow(() -> new IllegalStateException("No expirationDays configured"));

            tmpFiles.add(messageService.encryptFile(fileName, inStream, encryptionKey,
                Instant.now().plus(expirationDays, ChronoUnit.DAYS)));
        }

    };

    try {
        visitor.processRequest(req);
        binder.bind(propertyValues);
        binder.validate();
    } catch (final IllegalStateException ise) {
        errors.reject(null, ise.getMessage());
    }

    return tmpFiles;
}        
main