我有一個形式,並且一個場其綁定到一個用戶類,形式及其本領域<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;
}
使用下面的方法,這可能會對你有所幫助! - http://stackoverflow.com/questions/8723765/checkbox-values-do-not-bind-into-object-when-false – Niranjan