0

フォームにフィールドがあり、ユーザークラスにバインドされています。フォームには、このフィールドがあります

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

しかし、フォームを送信した瞬間にエラーが発生します

クライアントから送信された要求が構文的に正しくありませんでした。

私はfirebugでそれを検査し、これを得ました

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 は、チェックボックスの非表示の値であり、spring tag のデフォルトであると想定しています<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;
    }

フォーム.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 + "]";
    }


}

カテゴリ.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;
    }
4

1 に答える 1

0
  1. form:checkbox を削除した場合にフォーム送信が機能するかどうかを確認して、実際にこのチェックボックスが問題の原因であることを確認しましたか?
  2. サーバーのデバッグ ログを共有できますか
  3. @requestMapping 値を含むこのフォーム送信を処理しているコントローラー メソッドも共有します

ロールをカテゴリに変換するカスタム バインダーを追加できます カスタム プロパティ エディターを作成します

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 ()); }
于 2013-08-06T18:08:47.713 に答える