Example usage for org.springframework.validation BindingResult addError

List of usage examples for org.springframework.validation BindingResult addError

Introduction

In this page you can find the example usage for org.springframework.validation BindingResult addError.

Prototype

void addError(ObjectError error);

Source Link

Document

Add a custom ObjectError or FieldError to the errors list.

Usage

From source file:mx.edu.um.mateo.general.web.EmpresaController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpSession session, @RequestParam Long id, Model modelo, @ModelAttribute Empresa empresa,
        BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    log.debug("Elimina empresa");
    try {//from ww w . jav  a 2s .co  m
        String nombre = empresaDao.elimina(id);

        ambiente.actualizaSesion(session);

        redirectAttributes.addFlashAttribute("message", "empresa.eliminada.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (UltimoException e) {
        log.error("No se pudo eliminar el empresa " + id, e);
        bindingResult.addError(
                new ObjectError("empresa", new String[] { "ultima.empresa.no.eliminada.message" }, null, null));
        return "admin/empresa/ver";
    } catch (Exception e) {
        log.error("No se pudo eliminar la empresa " + id, e);
        bindingResult.addError(
                new ObjectError("empresa", new String[] { "empresa.no.eliminada.message" }, null, null));
        return "admin/empresa/ver";
    }

    return "redirect:/admin/empresa";
}

From source file:mx.edu.um.mateo.general.web.UsuarioController.java

@Transactional
@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(@RequestParam Long id, Model modelo, @ModelAttribute Usuario usuario,
        BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    log.debug("Elimina usuario");
    try {/*from   w  ww  .  ja v  a 2 s.  com*/
        String nombre = usuarioDao.elimina(id);
        redirectAttributes.addFlashAttribute("message", "usuario.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (UltimoException e) {
        log.error("No se pudo eliminar el usuario " + id, e);
        bindingResult.addError(
                new ObjectError("usuario", new String[] { "ultimo.usuario.no.eliminado.message" }, null, null));
        List<Rol> roles = usuarioDao.roles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/ver";
    } catch (Exception e) {
        log.error("No se pudo eliminar el usuario " + id, e);
        bindingResult.addError(
                new ObjectError("usuario", new String[] { "usuario.no.eliminado.message" }, null, null));
        List<Rol> roles = usuarioDao.roles();
        modelo.addAttribute("roles", roles);
        return "admin/usuario/ver";
    }

    return "redirect:/admin/usuario";
}

From source file:com.oak_yoga_studio.controller.CustomerController.java

@RequestMapping(value = "/addCredential", method = RequestMethod.POST)
public String addCredential(@Valid Credential credential, BindingResult result, HttpSession session) {
    String view = "redirect:/addCustomer";
    //dumb fix/*w  w  w .j  a v a2 s .  c  om*/
    boolean used = customerService.checkUserName(credential.getUserName());
    if (used) {
        FieldError f = new FieldError("credential", "userName", credential.getUserName(), false, null, null,
                "Username : " + credential.getUserName() + " already in use");
        result.addError(f);
    }
    if (!result.hasErrors()) {
        Customer c = (Customer) session.getAttribute("loggedUser");
        credential.setRole("ROLE_CUSTOMER");
        credential.setActive(true);
        session.setAttribute("credential", credential);

    } else {
        view = "addCredential";
    }
    return view;
}

From source file:info.gehrels.voting.web.ElectionCalculationController.java

@RequestMapping(value = "/resolveAmbiguity", method = POST)
public ModelAndView resolveAmbiguity(@RequestParam DateTime dateTimeTheCalculationStarted,
        @Valid AmbiguityResolverResultBuilderBean ambiguityResolverResultBuilder, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    AsyncElectionCalculation asyncElectionCalculation = electionCalculationsState
            .getHistoryOfElectionCalculations().get(dateTimeTheCalculationStarted);
    Snapshot snapshot = asyncElectionCalculation.getSnapshot();

    AmbiguityResolverResult<GenderedCandidate> build = null;
    if (!bindingResult.hasErrors()) {
        try {/*from w ww  . j a  va  2s. c  o m*/
            build = ambiguityResolverResultBuilder
                    .build(snapshot.getAmbiguityResulutionTask().getCandidatesToChooseFrom());
        } catch (NoSuchCandidateException e) {
            bindingResult
                    .addError(new ObjectError("unknownCandidate.ambiguityResolverResultBuilder.candidateName",
                            "The candidate " + e.candidateName + " is unknown"));
        }
    }

    if (bindingResult.hasErrors()) {
        return createModelAndView(snapshot, ambiguityResolverResultBuilder);
    } else {
        asyncElectionCalculation.setAmbiguityResolutionResult(build);
        redirectAttributes.addAttribute("dateTimeTheCalculationStarted", dateTimeTheCalculationStarted);
        return new ModelAndView("redirect:/showElectionCalculation");
    }
}

From source file:mx.edu.um.mateo.contabilidad.web.EjercicioController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam String id, Model modelo,
        @ModelAttribute Ejercicio ejercicio, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina ejercicio");
    try {//from   w  w w .j  a  va  2  s .  c  o  m
        EjercicioPK key = new EjercicioPK(id, ambiente.obtieneUsuario().getEmpresa().getOrganizacion());
        String nombre = ejercicioDao.elimina(key);

        redirectAttributes.addFlashAttribute("message", "ejercicio.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la ejercicio " + id, e);
        bindingResult.addError(
                new ObjectError("ejercicio", new String[] { "ejercicio.no.eliminado.message" }, null, null));
        return "contabilidad/ejercicio/ver/" + id;
    }

    return "redirect:/contabilidad/ejercicio";
}

From source file:mx.edu.um.mateo.general.web.OrganizacionController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpSession session, @RequestParam Long id, Model modelo,
        @ModelAttribute Organizacion organizacion, BindingResult bindingResult,
        RedirectAttributes redirectAttributes) {
    log.debug("Elimina organizacion");
    try {//from  w w  w  .  ja  v  a  2  s.c  om
        String nombre = organizacionDao.elimina(id);

        ambiente.actualizaSesion(session);

        redirectAttributes.addFlashAttribute("message", "organizacion.eliminada.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (UltimoException e) {
        log.error("No se pudo eliminar el organizacion " + id, e);
        bindingResult.addError(new ObjectError("organizacion",
                new String[] { "ultima.organizacion.no.eliminada.message" }, null, null));
        return "admin/organizacion/ver";
    } catch (Exception e) {
        log.error("No se pudo eliminar el organizacion " + id, e);
        bindingResult.addError(new ObjectError("organizacion",
                new String[] { "organizacion.no.eliminada.message" }, null, null));
        return "admin/organizacion/ver";
    }

    return "redirect:/admin/organizacion";
}

From source file:mx.edu.um.mateo.inventario.web.ProductoController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpServletRequest request, @RequestParam Long id, Model modelo,
        @ModelAttribute Producto producto, BindingResult bindingResult, RedirectAttributes redirectAttributes) {
    log.debug("Elimina producto");
    try {/*w  ww.  j a  v  a2  s . c  om*/
        String nombre = productoDao.elimina(id);

        redirectAttributes.addFlashAttribute("message", "producto.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (Exception e) {
        log.error("No se pudo eliminar la producto " + id, e);
        bindingResult.addError(
                new ObjectError("producto", new String[] { "producto.no.eliminado.message" }, null, null));
        return "inventario/producto/ver";
    }

    return "redirect:/inventario/producto";
}

From source file:com.assetmanager.controller.RegisterController.java

/**
 * Handle the create account form submission.
 *
 * @param register the register form bean
 * @param binding the binding result/*ww w. j  av  a 2s.  c o  m*/
 * @param request the HTTP servlet request
 * @return the path
 */
@RequestMapping(value = "/create", method = RequestMethod.POST)
public final String submit(@ModelAttribute(REGISTER) @Valid final Register register,
        final BindingResult binding, final HttpServletRequest request) {
    final Locale locale = localeResolver.resolveLocale(request);

    if (binding.hasErrors()) {
        return "create";
    }

    final UserAccount user = new UserAccount(register.getUsername());
    user.setDisplayName(register.getDisplayName());
    user.setEmail(register.getEmail());
    user.setPassword(passwordEncoder.encodePassword(register.getPassword(), user.getSalt()));

    try {
        userDetailsService.addUser(user, locale);
    } catch (DuplicateUserException e) {
        binding.addError(new FieldError(REGISTER, "username",
                messageSource.getMessage("create.error.username", null, locale)));
        return "create";
    }

    return "redirect:/register/success";
}

From source file:mx.edu.um.mateo.inventario.web.AlmacenController.java

@RequestMapping(value = "/elimina", method = RequestMethod.POST)
public String elimina(HttpSession session, Model modelo, @ModelAttribute Almacen almacen,
        BindingResult bindingResult, RedirectAttributes redirectAttributes, @RequestParam Long id) {
    log.debug("Elimina almacen");
    try {// ww  w.  j  av a  2s  .com
        Long empresaId = (Long) session.getAttribute("empresaId");
        String nombre = almacenDao.elimina(id, empresaId);

        ambiente.actualizaSesion(session);

        redirectAttributes.addFlashAttribute("message", "almacen.eliminado.message");
        redirectAttributes.addFlashAttribute("messageAttrs", new String[] { nombre });
    } catch (UltimoException e) {
        log.error("No se pudo eliminar el almacen " + id, e);
        bindingResult.addError(
                new ObjectError("almacen", new String[] { "ultimo.almacen.no.eliminado.message" }, null, null));
        return "inventario/almacen/ver";
    } catch (Exception e) {
        log.error("No se pudo eliminar la almacen " + id, e);
        bindingResult.addError(
                new ObjectError("almacen", new String[] { "almacen.no.eliminado.message" }, null, null));
        return "inventario/almacen/ver";
    }

    return "redirect:/inventario/almacen";
}

From source file:cz.muni.fi.mvc.controllers.DestinationController.java

/**
 * Creates a new Destination//from   ww w .  j a v a 2 s .c o  m
 * @param model display data
 * @return jsp page
 */
@RequestMapping(method = RequestMethod.POST, value = "/create")
public String create(@Valid @ModelAttribute("destinationCreate") DestinationCreationalDTO formBean,
        BindingResult bindingResult, Model model, RedirectAttributes redirectAttributes,
        UriComponentsBuilder uriBuilder) {
    if (bindingResult.hasErrors()) {
        for (FieldError fe : bindingResult.getFieldErrors()) {
            model.addAttribute(fe.getField() + "_error", true);
            log.trace("FieldError: {}", fe);
        }
        for (ObjectError ge : bindingResult.getGlobalErrors()) {
            log.trace("ObjectError: {}", ge);
        }
        return "destination/new";
    }
    try {
        if (destinationFacade.getDestinationWithLocation(formBean.getLocation()) == null) {
            bindingResult.addError(new FieldError("destinationCreate", "location",
                    "Destination was not created because it already exists."));
            model.addAttribute("location_error", true);
            return "destination/new";
        }

        Long id = destinationFacade.createDestination(formBean);
        redirectAttributes.addFlashAttribute("alert_info", "Destination with id: " + id + " was created");
    } catch (Exception ex) {
        model.addAttribute("alert_danger", "Destination was not created because of some unexpected error");
        redirectAttributes.addFlashAttribute("alert_danger",
                "Destination was not created because it already exists.");
    }
    return "redirect:" + uriBuilder.path("/destination").toUriString();
}