2013-08-06 43 views
0

我有一個形式,並且一個場其綁定到一個用戶類,形式及其本領域<form:checkbox>隱藏的值搞亂我的表單?

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

但是在提交表單中的錯誤的時刻出現

由所發送的請求客戶端在語法上不正確。

我用螢火檢查,並得到這個

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 

的_acceptTerms其隱藏價值的複選框,因爲我認爲它春天標籤<form:checkbox>的默認。

這對我產生3個問題: 請問這個字段(_acceptTerms)與我的表單提交混亂嗎? 爲什麼_acceptTerms始終設置爲on? 如果這個領域確實搞砸了我的表格,我該如何擺脫它,或者我應該如何處理它?添加到用戶模型?

在此先感謝

編輯

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> 

登錄

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; 
    } 
+0

使用下面的方法,這可能會對你有所幫助! - http://stackoverflow.com/questions/8723765/checkbox-values-do-not-bind-into-object-when-false – Niranjan

回答

0
  1. 你檢查,如果你刪除表格表單提交作品:checbox,保證確實該複選框導致問題
  2. 可以分享調試日誌的服務器
  3. 也分享你的控制器方法,這使得這個表單提交包括@requestMapping值

您可以添加自定義粘結劑ROL轉換成 類創建自定義屬性編輯器

public class CategoryEditor extends PropertyEditorSupport { 

@Override 

public void setAsText(String text) { 

Category cat = new Category(); 

//set rol vlaue in cat 

setValue(cat); 

} 

現在在你的控制器

@InitBinder 

    public void initBinderAll(WebDataBinder binder) { 

    binder.registerCustomEditor(Category .class, new CategoryEditor()); } 
+0

好的,所以我刪除了複選框,但問題沒有解決,所以複選框不是罪魁禍首。 我不知道在哪裏或如果服務器調試日誌啓用我只是使用一個記錄器,我用作println。 – Ccortina

+0

你是否能夠檢查當你提交表單時你的控制器被調用?你也可以請共享服務器日誌和你的春天配置文件 – coder

+0

我剛剛檢查了日誌和我的錯誤,我的領域滾動它的一個實體,當我嘗試將它傳遞給它的模型崩潰,因爲它不是同一種。但我不知道如何解析該字段。 – Ccortina