简体   繁体   English

Spring MVC - 如何将继承类型从jsp传递给控制器

[英]Spring MVC - how to pass an inheriting type from jsp to controller

I have a controller that gets a certain DTO as a parameter: 我有一个控制器,将某个DTO作为参数:

@Controller
public class MyController {

   @RequestMapping(value = "/request", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
   @ResponseStatus(value = HttpStatus.OK)
   @ResponseBody
   public int processRequest(@RequestBody BaseRequestDTO baseRequestDTO, HttpServletRequest request) {
       ...
   }

}

BaseRequestDTO has a field, let's say String a . BaseRequestDTO有一个字段,比如String a

I have another DTO that extends BaseRequestDTO - MyRequestDTO. 我有另一个扩展BaseRequestDTO的DTO - MyRequestDTO。 MyRequestDTO also has a field, let's say String b . MyRequestDTO也有一个字段,比如String b I'm trying to pass a MyRequestDTO from a jsp form to the controller: 我正在尝试将MyRequestDTO从jsp表单传递给控制器​​:

$.ajax({
        type : "POST",
        url : URL + "/request",
        data : JSON.stringify(eval({
             "a" : "hello",
             "b" : "world"
        })),
        ...
});

Now when I try to send the parameters I get this error: 现在,当我尝试发送参数时,我收到此错误:

Could not read JSON: Unrecognized field "b"

Because obviously BaseRequestDTO doesn't have that field. 因为很明显BaseRequestDTO没有那个字段。

EDIT: The message converters that are defined in the application context: 编辑:在应用程序上下文中定义的消息转换器:

<property name="messageConverters">
        <list>
            <bean
                class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            </bean>
            <bean class="org.springframework.http.converter.FormHttpMessageConverter" />
            <bean
                class="org.springframework.http.converter.StringHttpMessageConverter" />
        </list>
    </property>

So how can I pass an inheriting type (that has additional fields to the base class) as a parameter to the controller? 那么如何将继承类型(具有附加字段到基类)作为参数传递给控制器​​? Does anyone know of a solution to that? 有谁知道解决方案?

There is support for this in Jackson , try specifying a property in the support class that holds the concrete type information: 在Jackson中支持这一点,尝试在支持类中指定一个包含具体类型信息的属性:

@JsonTypeInfo(use=JsonTypeInfo.Id.CLASS, include=JsonTypeInfo.As.PROPERTY, property="@class")
public abstract class BaseRequestDTO {
  ...
} 

And on the JSON, specify the concrete type: 在JSON上,指定具体类型:

{
  "@class" : "com.yourpackage.MyRequestDTO",
       "a" : "hello",
       "b" : "world"
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM