0

i have a field in a form and its bound to an user class, in the form its this field

<tr>
    <td>AcceptTerms:</td>
    <td><form:checkbox path="acceptTerms"/><td>
</tr>

but at the moment of submitting the form an error arises

The request sent by the client was syntactically incorrect.

i inspected it with firebug and got this

Parameters   application/x-www-form-urlencoded
_acceptTerms    on
email   ZX
password    ZXZX
rol 2
username    ZxZ
Fuente
username=ZxZ&password=ZXZX&email=ZX&rol=2&_acceptTerms=on

the _acceptTerms its a hidden value for the checkbox that as i assume it a default of spring tag <form:checkbox>.

this arises 3 questions for me: does this field (_acceptTerms) mess with my form submit? why is _acceptTerms always set to on? if this field does indeed mess up my form how can i get rid of it or how should i process it? add to the user model?

thanks in advance

Edit

package com.carloscortina.paidosSimple.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.carloscortina.paidosSimple.model.Categoria;
import com.carloscortina.paidosSimple.model.Personal;
import com.carloscortina.paidosSimple.model.Usuario;
import com.carloscortina.paidosSimple.service.CategoriaService;
import com.carloscortina.paidosSimple.service.PersonalService;
import com.carloscortina.paidosSimple.service.UsuarioService;

@Controller
public class PersonalController {

    private static final Logger logger = LoggerFactory.getLogger(PersonalController.class);

    @Autowired
    private PersonalService personalService;

    @Autowired
    private UsuarioService usuarioService;

    @Autowired
    private CategoriaService categoriaService;

    @RequestMapping(value="/usuario/add")
    public ModelAndView addUsuarioPage(){
        ModelAndView modelAndView = new ModelAndView("add-usuario-form");
        modelAndView.addObject("categorias",categorias());
        modelAndView.addObject("user", new Usuario());
        return modelAndView;
    }

    @RequestMapping(value="/usuario/add/process",method=RequestMethod.POST)
    public ModelAndView addingUsuario(@ModelAttribute Usuario user){
        ModelAndView modelAndView = new ModelAndView("add-personal-form");
        usuarioService.addUsuario(user);
        logger.info(modelAndView.toString());
        String message= "Usuario Agregado Correctamente.";
        modelAndView.addObject("message",message);
        modelAndView.addObject("staff",new Personal());

        return modelAndView;
    }

    @RequestMapping(value="/personal/list")
    public ModelAndView listOfPersonal(){
        ModelAndView modelAndView = new ModelAndView("list-of-personal");

        List<Personal> staffMembers = personalService.getAllPersonal();
        logger.info(staffMembers.get(0).getpNombre());
        modelAndView.addObject("staffMembers",staffMembers);

        return modelAndView;
    }

    @RequestMapping(value="/personal/edit/{id}",method=RequestMethod.GET)
    public ModelAndView editPersonalPage(@PathVariable int id){
        ModelAndView modelAndView = new ModelAndView("edit-personal-form");
        Personal staff = personalService.getPersonal(id);
        logger.info(staff.getpNombre());
        modelAndView.addObject("staff",staff);

        return modelAndView;
    }

    @RequestMapping(value="/personal/edit/{id}", method=RequestMethod.POST)
    public ModelAndView edditingPersonal(@ModelAttribute Personal staff, @PathVariable int id) {

        ModelAndView modelAndView = new ModelAndView("home");

        personalService.updatePersonal(staff);

        String message = "Personal was successfully edited.";
        modelAndView.addObject("message", message);

        return modelAndView;
    }

    @RequestMapping(value="/personal/delete/{id}", method=RequestMethod.GET)
    public ModelAndView deletePersonal(@PathVariable int id) {
        ModelAndView modelAndView = new ModelAndView("home");
        personalService.deletePersonal(id);
        String message = "Personal was successfully deleted.";
        modelAndView.addObject("message", message);
        return modelAndView;
    }

    private Map<String,String> categorias(){
        List<Categoria> lista = categoriaService.getCategorias();

        Map<String,String> categorias = new HashMap<String, String>();
        for (Categoria categoria : lista) {
            categorias.put(Integer.toString(categoria.getId()), categoria.getCategoria());
        }
        return categorias;
    }

Form.jsp

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>

<head>
    <title>Add personal page</title>
</head>
<body>
    <p>${message}<br>
    <h1>Add User Page</h1>
    <p>Here you can add a new staff member.</p>
    <form:form method="POST" commandName="user" action="${pageContext.request.contextPath}/usuario/add/process" >
    <table>
        <tbody>
            <tr>
                <td>Nombre de Usuario:</td>
                <td><form:input path="username"/><td>
            </tr>
            <tr>
                <td>Contraseña:</td>
                <td><form:password path="password"/><td>
            </tr>
            <tr>
                <td>Email:</td>
                <td><form:input path="email"/><td>
            </tr>
            <tr>
                <td>Categoria:</td>
                <td><form:select path="rol">
                    <form:options items="${categorias}" />
                </form:select><td>
            </tr>
            <tr>
                <td>AcceptTerms:</td>
                <td><form:checkbox path="acceptTerms"/><td>
            </tr>
            <tr>
                <td><input type="submit" value="Registrar"><td>
            </tr>
        </tbody>
    </table>
    </form:form>

    <p><a href="${pageContext.request.contextPath}/index">Home Page</a></p>
</body>

Log

DEBUG: org.springframework.web.servlet.DispatcherServlet - DispatcherServlet with name 'appServlet' processing POST request for [/paidosSimple/usuario/add/process]
DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Looking up handler method for path /usuario/add/process
DEBUG: org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Returning handler method [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]
DEBUG: org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'personalController'
DEBUG: org.springframework.beans.BeanUtils - No property editor [com.carloscortina.paidosSimple.model.CategoriaEditor] found for type com.carloscortina.paidosSimple.model.Categoria according to 'Editor' suffix convention
DEBUG: org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'usuario' on field 'rol': rejected value [2]; codes [typeMismatch.usuario.rol,typeMismatch.rol,typeMismatch.com.carloscortina.paidosSimple.model.Categoria,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.carloscortina.paidosSimple.model.Categoria' for property 'rol'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.carloscortina.paidosSimple.model.Categoria] for property 'rol': no matching editors or conversion strategy found]
DEBUG: org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'usuario' on field 'rol': rejected value [2]; codes [typeMismatch.usuario.rol,typeMismatch.rol,typeMismatch.com.carloscortina.paidosSimple.model.Categoria,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.carloscortina.paidosSimple.model.Categoria' for property 'rol'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.carloscortina.paidosSimple.model.Categoria] for property 'rol': no matching editors or conversion strategy found]
DEBUG: org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver - Resolving exception from handler [public org.springframework.web.servlet.ModelAndView com.carloscortina.paidosSimple.controller.PersonalController.addingUsuario(com.carloscortina.paidosSimple.model.Usuario)]: org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'usuario' on field 'rol': rejected value [2]; codes [typeMismatch.usuario.rol,typeMismatch.rol,typeMismatch.com.carloscortina.paidosSimple.model.Categoria,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.carloscortina.paidosSimple.model.Categoria' for property 'rol'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.carloscortina.paidosSimple.model.Categoria] for property 'rol': no matching editors or conversion strategy found]
DEBUG: org.springframework.web.servlet.DispatcherServlet - Null ModelAndView returned to DispatcherServlet with name 'appServlet': assuming HandlerAdapter completed request handling
DEBUG: org.springframework.web.servlet.DispatcherServlet - Successfully completed request

Usuario.java

package com.carloscortina.paidosSimple.model;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="Usuario")
public class Usuario {

    private Integer id;
    private String username,password,email;
    boolean acceptTerms = false,active=true;
    private Categoria rol;

    /**
     * @return the id
     */
    @Id
    @GeneratedValue
    @Column(name="id")
    public Integer getId() {
        return id;
    }
    /**
     * @return the rol
     */
    @OneToOne(cascade=CascadeType.ALL)
    @JoinTable(name="usuario_rol",
            joinColumns={@JoinColumn(name="Usuario",referencedColumnName="id")},
            inverseJoinColumns={@JoinColumn(name="Rol",referencedColumnName="id")})
    public Categoria getRol() {
        return rol;
    }
    /**
     * @param rol the rol to set
     */
    public void setRol(Categoria rol) {
        this.rol = rol;
    }
    /**
     * @param id the id to set
     */
    public void setId(Integer id) {
        this.id = id;
    }
    /**
     * @return the username
     */
    @Column(name="Username")
    public String getUsername() {
        return username;
    }
    /**
     * @param username the username to set
     */
    public void setUsername(String username) {
        this.username = username;
    }
    /**
     * @return the password
     */
    @Column(name="Password")
    public String getPassword() {
        return password;
    }
    /**
     * @param password the password to set
     */
    public void setPassword(String password) {
        this.password = password;
    }
    /**
     * @return the email
     */
    @Column(name="Email")
    public String getEmail() {
        return email;
    }
    /**
     * @param email the email to set
     */
    public void setEmail(String email) {
        this.email = email;
    }
    /**
     * @return the acceptTerms
     */
    @Column(name="acceptTerms")
    public boolean isAcceptTerms() {
        return acceptTerms;
    }
    /**
     * @param acceptTerms the acceptTerms to set
     */
    public void setAcceptTerms(boolean acceptTerms) {
        this.acceptTerms = acceptTerms;
    }

    public boolean isActive() {
        return active;
    }
    public void setActive(boolean active) {
        this.active = active;
    }
    /* (non-Javadoc)
     * @see java.lang.Object#toString()
     */
    @Override
    public String toString() {
        return "Usuario [id=" + id + ", username=" + username + ", password="
                + password + ", email=" + email + ", acceptTerms="
                + acceptTerms + "]";
    }


}

Categoria.java

package com.carloscortina.paidosSimple.model;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="Categoria")
public class Categoria {

    private int id;
    private String categoria,descripcion;
    private Set<Usuario> UserRoles;

    /**
     * @return the userRoles
     */
    @OneToMany(cascade=CascadeType.ALL)
    @JoinTable(name="usuario_rol",
            joinColumns={@JoinColumn(name="Categoria",referencedColumnName="id")},
            inverseJoinColumns={@JoinColumn(name="Usuario",referencedColumnName="id")})
    public Set<Usuario> getUserRoles() {
        return UserRoles;
    }
    /**
     * @param userRoles the userRoles to set
     */
    public void setUserRoles(Set<Usuario> userRoles) {
        UserRoles = userRoles;
    }
    /**
     * @return the id
     */
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    /**
     * @param id the id to set
     */
    public void setId(int id) {
        this.id = id;
    }
    /**
     * @return the categoria
     */
    public String getCategoria() {
        return categoria;
    }
    /**
     * @param categoria the categoria to set
     */
    public void setCategoria(String categoria) {
        this.categoria = categoria;
    }
    /**
     * @return the descripcion
     */
    public String getDescripcion() {
        return descripcion;
    }
    /**
     * @param descripcion the descripcion to set
     */
    public void setDescripcion(String descripcion) {
        this.descripcion = descripcion;
    }
Ccortina
  • 587
  • 14
  • 31
  • This may be helpful to you!! - http://stackoverflow.com/questions/8723765/checkbox-values-do-not-bind-into-object-when-false – Niranjan Aug 06 '13 at 21:23

1 Answers1

0
  1. Have you checked if your form submission works if you remove form:checbox, to ensure that indeed this checkbox is causing the issue
  2. can you share debug logs of server
  3. Also share your controller method that is hadnling this form submission including @requestMapping value

you can add a custom binder to convert rol into category Create a custom property editor

public class CategoryEditor extends PropertyEditorSupport {

@Override

public void setAsText(String text) {

Category cat = new Category ();

//set rol vlaue in cat

setValue(cat);

}

now use following method in your controller

 @InitBinder

    public void initBinderAll(WebDataBinder binder) {

    binder.registerCustomEditor(Category .class,  new CategoryEditor ()); }
coder
  • 4,458
  • 2
  • 17
  • 23
  • Ok, so i deleted the checkbox but the problem didnt solve, so the checkbox isnt the culprit. Im dont know where are or if the server debug logs are enabled i just use a logger that i use as a println. – Ccortina Aug 06 '13 at 18:35
  • were you able to check that when you submit form does your controller gets called ? also can you please share server logs and your spring config files – coder Aug 06 '13 at 18:52
  • i just checked the log and my error its that my field rol its an entity and when i try to pass it to the model it crashes because its not of the same kind. but i dont know how can i parse the field. – Ccortina Aug 06 '13 at 18:53
  • also if you can share class Categoria – coder Aug 06 '13 at 18:57
  • Thanks i just tried but now i get a Field error in object 'usuario' on field 'rol': rejected value [2]; codes [methodInvocation.usuario.rol,methodInvocation.rol,methodInvocation.com.carloscortina.paidosSimple.model.Categoria,methodInvocation]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [usuario.rol,rol]; arguments []; default message [rol]]; default message [Property 'rol' threw exception; nested exception is java.lang.NullPointerException] – Ccortina Aug 06 '13 at 21:07
  • in case issue is still not resolved, kindly share your CategoryEditor class – coder Aug 07 '13 at 04:39
  • Thanks,the problem was solved. when declaring the InitBinder the new CategoriaService() made the bean null so the auotwired was usless. im facing a new problem because the value of categoria its not being binded to de form after the propertyEditor. http://stackoverflow.com/questions/18093764/field-not-binding-to-form-after-custom-propertyeditor thanks – Ccortina Aug 07 '13 at 05:22