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

The following are Jave code examples for showing how to use hasErrors() of the org.springframework.validation.BindingResult class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: Spring-Security-Third-Edition   File: EventsController.java   View Source Code Vote up 9 votes
@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 2
Project: nixmash-blog   File: AdminPostsController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/categories/new", method = RequestMethod.POST)
public String addCategory(@Valid CategoryDTO categoryDTO,
                          BindingResult result,
                          SessionStatus status,
                          RedirectAttributes attributes) {
    if (result.hasErrors()) {
        return ADMIN_CATEGORIES_VIEW;
    } else {

        Category category = postService.createCategory(categoryDTO);
        logger.info("Category Added: {}", category.getCategoryValue());
        status.setComplete();

        webUI.addFeedbackMessage(attributes, FEEDBACK_MESSAGE_CATEGORY_ADDED, category.getCategoryValue());
        return "redirect:/admin/posts/categories";
    }
}
 
Example 3
Project: Spring-Security-Third-Edition   File: SignupController.java   View Source Code Vote up 6 votes
@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:/";
}
 
Example 4
Project: zkAdmin   File: CoreController.java   View Source Code Vote up 6 votes
/**
 * 保存连接信息
 * @param form
 * @param bindingResult
 * @param session
 * @return
 */
@RequestMapping("connection/save.json")
@ResponseBody
public Map<String,Object> saveConnection(@Valid ZookeeperConnectForm form, BindingResult bindingResult, HttpSession session){
    if(bindingResult.hasErrors()){
        return Result.formErrorWrapper(bindingResult.getFieldError().getField(),bindingResult.getFieldError().getDefaultMessage());
    }
    ConnectionInfo connInfo = new ConnectionInfo();
    connInfo.setConnectUrl(form.getConnectString());
    connInfo.setAcl(form.getAcl());
    connInfo.setOwner(ShiroUtils.getCurrUser().getLoginName());
    connInfo.setRemark(form.getRemark()==null?"未命名":form.getRemark());
    connInfo.setSessionTimeout(form.getSessionTimeout());
    try {
        coreService.saveConnection(connInfo);
    } catch (DataExistException e) {
        return Result.errorWrapper(e.getMessage());
    }

    return Result.SIMPLE_SUCCESS;
}
 
Example 5
Project: uis   File: AdminUsersController.java   View Source Code Vote up 6 votes
@PostMapping("/create")
public String createUser(@Valid CreateUserForm form,
                         BindingResult bindingResult,
                         RedirectAttributes redirectAttributes) {
    if (bindingResult.hasErrors()) {
        redirectAttributes.addFlashAttribute("flashMessage", "admin.users.create.error." + bindingResult.getFieldError().getField());

        return "redirect:/admin/users";
    }
    boolean error = false;
    try{
    	userCreationService.create(form.toUisUser());
    }catch(ValidationException e){
    	error = true;
        redirectAttributes.addFlashAttribute("flashMessage", "admin.users.create.error.email");
    }
    if(!error){
    	redirectAttributes.addFlashAttribute("flashMessage", "admin.users.create.success");
    }
    
    return "redirect:/admin/users";
}
 
Example 6
Project: nixmash-blog   File: AdminController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/users/new", method = RequestMethod.POST)
public String addUser(@Valid UserDTO userDTO,
                      BindingResult result, SessionStatus status, Model model,
                      RedirectAttributes attributes) {
    if (result.hasErrors()) {
        model.addAttribute("authorities", userService.getRoles());
        return ADMIN_USERFORM_VIEW;
    } else {
        userDTO.setSignInProvider(SignInProvider.SITE);
        User added = userService.create(userDTO);
        logger.info("Added user with information: {}", added);
        status.setComplete();

        webUI.addFeedbackMessage(attributes, FEEDBACK_MESSAGE_KEY_USER_ADDED, added.getFirstName(),
                added.getLastName());

        return "redirect:/admin/users";
    }
}
 
Example 7
Project: Monsters_Portal   File: ComprarController.java   View Source Code Vote up 6 votes
@RequestMapping(value = "/FinalizarCompraSegura")
public String comprar(Model model, @Valid Pedido pedido, HttpSession session, BindingResult result) {
	
	Cliente cliente = (Cliente) session.getAttribute("clienteLogado");
	Carrinho carrinho = (Carrinho) session.getAttribute("carrinho");
	
	// Gerar numero randomico
	int min = 100000000;//na vdd s�o 14 campos
	int max = 999999999;
	int numb_ped = ThreadLocalRandom.current().nextInt(min, max + 1);
	
	pedido.setNumero_ped(numb_ped);
	
	if(result.hasErrors()) {
	    return "forward:forma_de_pagamento";
	} else {
		carrinho.removeAll();
		session.setAttribute("carrinho", carrinho);
		Long id = dao.create(pedido, carrinho, cliente);
		return "redirect:boleto/"+id;
	}
}
 
Example 8
Project: Spring-Security-Third-Edition   File: EventsController.java   View Source Code Vote up 6 votes
@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 9
Project: Spring-Security-Third-Edition   File: SignupController.java   View Source Code Vote up 5 votes
@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 10
Project: Spring-Security-Third-Edition   File: SignupController.java   View Source Code Vote up 5 votes
@PostMapping(value="/signup/new")
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 11
Project: Spring-Security-Third-Edition   File: SignupController.java   View Source Code Vote up 5 votes
@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 12
Project: Spring-Security-Third-Edition   File: SignupController.java   View Source Code Vote up 5 votes
@PostMapping(value="/signup/new")
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
Project: springboot-learning-example   File: UserController.java   View Source Code Vote up 5 votes
/**
 *  创建用户
 *    处理 "/users" 的 POST 请求,用来获取用户列表
 *    通过 @ModelAttribute 绑定参数,也通过 @RequestParam 从页面中传递参数
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public String postUser(ModelMap map,
                       @ModelAttribute @Valid User user,
                       BindingResult bindingResult) {

    if (bindingResult.hasErrors()) {
        map.addAttribute("action", "create");
        return "userForm";
    }

    userService.insertByUser(user);

    return "redirect:/users/";
}
 
Example 14
Project: Spring-5.0-Cookbook   File: FormController.java   View Source Code Vote up 5 votes
@RequestMapping(method=RequestMethod.POST)
public String submitForm(Model model, @ModelAttribute("employeeForm") @Validated EmployeeForm employeeForm, BindingResult result ){
	model.addAttribute("employeeForm", employeeForm);
	validator.validate(employeeForm, result);
	if(result.hasErrors()){
		return "form_page";
	}
	return "success_page";
}
 
Example 15
Project: Monsters_Portal   File: BannerController.java   View Source Code Vote up 5 votes
@RequestMapping("Admin/CreateBanner")
public String create(HttpSession session, @Valid Banner banner, BindingResult result) {
	if(Permissoes.checar(session, EnumMetodo.CRIAR, entidade)){				//	Checar Permissão
		if(result.hasErrors()) {											//	Se houver erro na validação
		    return "forward:banner";										//	Volte para a página de adição
		} else {
			dao.create(banner);												//	Ação no banco
			relatorio.gerarRelatorio(session, EnumMetodo.CRIAR, entidade);	//	Relatório
			return "redirect:banner";										//	Retorna para o método Read
		}
	}
	return "403";
}
 
Example 16
Project: Spring-Security-Third-Edition   File: SignupController.java   View Source Code Vote up 5 votes
@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
Project: Monsters_Portal   File: ImagemController.java   View Source Code Vote up 5 votes
@RequestMapping("Admin/Updateimagem")
public String update(@Valid Imagem imagem, BindingResult result) {

	if(result.hasErrors()) {												//	Se houver erro na validação
	    return "forward:Produto";											//	Volte
	} else {
		dao.update(imagem);													//	Ação no banco
		return "redirect:Produto";											//	Retorna para o método Read
	}
}
 
Example 18
Project: Plum   File: AdminArticleController.java   View Source Code Vote up 5 votes
@ApiOperation(value="admin-新增文章")
@PostMapping
public RestResponse addArticle(@RequestBody @Valid AddArticleParam param, BindingResult result) {
    if (result.hasErrors()) {
       return buildErrors(result.getAllErrors());
    }
    return RestResponse.success(articleService.addArticle(param));
}
 
Example 19
Project: AntiSocial-Platform   File: ArticleRestController.java   View Source Code Vote up 5 votes
@RequestMapping(value = "/comment/add", method = RequestMethod.POST)
public CommentDTO createComment(@Valid @RequestBody CommentDTO commentDTO, BindingResult br){
    if(br.hasErrors()){return null;}
    if(userService.getPrincipal() == null){
        CommentDTO errorDTO = new CommentDTO();
        errorDTO.setErrorAccess(true);
        return errorDTO;
    }
    User user = userService.getUserBySsoId(userService.getPrincipal(), true);
    Comment comment = new Comment(user.getName(), user.getSsoId(), commentDTO.getCommentBody());
    articleService.addComment(comment, commentDTO.getArticleID());
    Long commentID = commentService.saveComment(comment);
    return new CommentDTO(user.getName(), user.getSsoId(), commentID, commentDTO.getCommentBody(), "just now", commentDTO.getArticleID(), false);
}
 
Example 20
Project: AntiSocial-Platform   File: UserController.java   View Source Code Vote up 4 votes
@RequestMapping(value = "/update", method = RequestMethod.POST)
public String updateUser(@Valid @ModelAttribute UserSettingsDTO userSettingsDTO, BindingResult br, Model model, RedirectAttributes attr){
    if(br.hasErrors()){
        attr.addFlashAttribute("userSettingsDTO", userSettingsDTO);
        attr.addFlashAttribute("updateError", br.getAllErrors());
        return "redirect:/user/"+userSettingsDTO.getSsoId()+"/settings?updateError";
    }

    User user = userService.getUserBySsoId(userSettingsDTO.getSsoId(), true);
    if(user == null){
        attr.addFlashAttribute("error", "User does not exist.");
        return "redirect:/error";
    }
    if(!user.getSsoId().equals(userService.getPrincipal())){
        attr.addFlashAttribute("error", "You do not have the permission to access this page.");
        return "redirect:/error";
    }

    if(userService.isUserExistEmail(userSettingsDTO.getEmail()) && !user.getEmail().equals(userSettingsDTO.getEmail())){
        attr.addFlashAttribute("userSettingsDTO", userSettingsDTO);
        List<ObjectError> list = new ArrayList<ObjectError>();
        list.add(new ObjectError("userSettingsDTO","User with the given email already exists!"));
        attr.addFlashAttribute("updateError", list);
        return "redirect:/user/"+userSettingsDTO.getSsoId()+"/settings?updateError";
    }

    user.setEmail(userSettingsDTO.getEmail());
    /*if(!user.getPassword().equals(userDTO.getPassword())){
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
    }*/
    /*if(!passwordEncoder.matches(userDTO.getPassword(), user.getPassword())){
        user.setPassword(passwordEncoder.encode(userDTO.getPassword()));
    }*/
    if (userSettingsDTO.getPassword() != null && userSettingsDTO.getPasswordChange() != null) {
        user.setPassword(passwordEncoder.encode(userSettingsDTO.getPassword()));
    }

    user.setName(userSettingsDTO.getName());
    user.getUserDetail().setUserBio(userSettingsDTO.getUserBio());

    try {
        userService.saveUser(user);
    } catch (Exception e) {
        attr.addFlashAttribute("error", "Could not update user. Please contact our support team.");
        return "redirect:/error";
    }

    return "redirect:/user/"+userSettingsDTO.getSsoId()+"/settings?success";

}