@ModelAttribute和抽象类 [英] @ModelAttribute and abstract class

查看:130
本文介绍了@ModelAttribute和抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有类似的问题。其中给出的示例过于零碎且不清楚。

I know that there have been similar questions. The examples given in them are too fragmentary and unclear.

我需要通过发送POST的页面上的表单编辑实体。标准方法是控制器中使用@ModelAttribute和validator参数的方法。如果一个表单服务于抽象类的某个子类,则生成必要字段没有问题,但控制器中存在问题。

I need to edit the entities through a form on the page that sends the POST. The standard method is a method in the controller uses the parameter with @ModelAttribute and validator. If one form serves some subclass of an abstract class, there are no problems with the generation of the necessary fields, but there is a problem in the controller.

据我所知它,@ ModelAttribute以这种方式工作:它初始化所需的对象类,然后收集他的请求参数的字段。当然,如果对象是抽象类,则无法初始化。因此,表单有一个字段,指示要初始化的子类。接下来,我们需要代码的和平,它将读取此属性并初始化正确的子类。它应该是什么?我看到了关于Converter,PrepertyEditor,WebDataBinder的零碎例子,但很难将所有内容放在一起。

As I understand it, @ModelAttribute works this way: it initializes the desired object class, and then collects his fields of the parameters of the request. Of course, if the object is an abstract class, it can not be initialized. Therefore, the form has a field that will indicate what subclass to initialize. Next, we need peace of code, that will read this attribute and initialize the correct subclass. What should it be? I saw fragmentary examples about the Converter, PrepertyEditor, WebDataBinder, but difficult to put everything together.

所以。有以下层次结构:

So. There are the following hierarchy:

public abstract class Person {role, name, email, password ...}
public class Student extends Person {}
public class Lecturer extends Person {}

有一个控制器及其中的方法:

There is a controller and methods in it:

@RequestMapping (Path = "/ persons / uid {personId} / edit",
                method = RequestMethod.GET)
public String editPerson (@PathVariable Integer personId, Model model) {
    Person find = personDAO.read (personId);
    model.addAttribute ( "person", find);
    return "editPerson";
}

@RequestMapping (Path = "/ persons / uid {personId} / edit",
                method = RequestMethod.POST)
public String editPersonPost (@PathVariable Integer personId,
        @Valid @ModelAttribute ( "Person") Person person,
        BindingResult result) {
    if (result.hasErrors ()) return "editPerson error = true?";
    personDAO.update (person);
    return "redirect: / persons / uid" + personId + "saved = true?";
}

还有一个带有以下形式的JSP:

And there is a JSP with a form:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<h1>${person.name}</h1>

<form:form action="edit" method="post" commandName="person">
    <input type="hidden" value="${person.role}" name="person_type" />
    <table>
        <tr>
            <td>Password</td>
            <td><form:input path="httpAuth.password" type="password"/></td>
            <td><form:errors path="httpAuth.password" cssClass="error"></form:errors></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><form:input path="email" /></td>
            <td><form:errors path="email" cssClass="error"></form:errors></td>
        </tr>
        <tr>
            <td></td>
            <td><input type="submit" value="Save"></td>
            <td></td>
        </tr>
    </table>
</form:form>

此外,转换器已编写,但我怀疑是否有必要,否则就这样做(继承另一个类......)

Also, the converter has been written, but I doubt whether it is necessary, or else do it (inheriting another class ...)

public class PersonConverter implements Converter <String, Person> {

public Person convert (String personType) {
    Person person = null;
    switch (personType) {
        case "Student":
            person = new Student ();
            break;
        case "Lecturer":
            person = new Lecturer ();
            break;
        default:
            throw new IllegalArgumentException (
                    "Unknown person type:" + personType);
    }
    return person;
}}

哪些是在ConversionService注册的

Which is registered with ConversionService

<bean class="org.springframework.context.support.ConversionServiceFactoryBean"
    id="theConversionService">
    <property name="converters">
        <list>
            <bean class="schedule.service.PersonConverter"></bean>
        </list>
    </property>
</bean>
<mvc:annotation-driven conversion-service="theConversionService" validator="validator"/>

然而,缺少某些东西,这是一种需要 person_type <的方法/ code>来自请求参数并将其提供给转换器,它将通过自动绑定机制返回控制器方法的结果。

Nevertheless, something is missing, that is a method that will take person_type from request parameters and give it to converter, and it will return a result of the method the controller via the automatic binding mechanisms.

请帮助我。

推荐答案

您只需要确保下面的元素

You just need to ensure that the element below

<input type="hidden" value="${person.role}" name="person_type" />

将其命名属性更改为人

<input type="hidden" value="${person.role}" name="person" />

以便它与控制器中的model属性匹配

so that it matches the model attribute in your controller

public String editPersonPost (@PathVariable Integer personId,
        @Valid @ModelAttribute ( "person") Person person,
        BindingResult result)

这是它的工作原理。

收到请求时并且Spring需要创建它检查属性是否已存在的模型属性。如果它不存在并且没有匹配名称的请求参数,则使用参数类的默认构造函数创建一个新对象

When a request is received and Spring needs to create the model attribute it checks if the attribute already exists. If it doesn`t exist and there is no request parameter of matching name it creates a new object using the default constructor of the parameter class

如果它存在并匹配参数键入它继续绑定请求参数。如果它不兼容或者同名的请求参数可用,它会尝试查找能够将当前值转换为所需类型的转换器

If it exists and matches the argument type it proceeds to bind the request parameters. If it is not compatible or a request parameter of same name is available it tries to find a converter capable of converting the current value to the required type

如果转换成功,将请求参数绑定到结果,否则抛出异常

If conversion is successful it binds the request parameters to the result otherwise it throws an Exception

在您的情况下,person属性作为String发送。 Spring将尝试将其转换为Person。在绑定

In your case the person attribute is sent as a String. Spring will attempt to convert it to a Person. It picks your PersonConverter to do the conversion to an appropriate subclass before binding

这篇关于@ModelAttribute和抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆