【问题标题】:Spring MVC - how to pass an inheriting type from jsp to controllerSpring MVC - 如何将继承类型从 jsp 传递给控制器
【发布时间】:2014-02-02 11:23:34
【问题描述】:

我有一个控制器,它获取某个 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 有一个字段,比如说String a。

我有另一个扩展 BaseRequestDTO 的 DTO - MyRequestDTO。 MyRequestDTO 也有一个字段,比如说String b。 我正在尝试将 MyRequestDTO 从 jsp 表单传递给控制器​​:

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

现在,当我尝试发送参数时,出现此错误:

Could not read JSON: Unrecognized field "b"

因为显然 BaseRequestDTO 没有那个字段。

编辑:在应用程序上下文中定义的消息转换器:

<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>

那么如何将继承类型(具有附加字段到基类)作为参数传递给控制器​​?有谁知道解决办法吗?

【问题讨论】:

  • 能否指定你在应用上下文配置中定义的jacksonMessageConverter

标签: java json spring jsp spring-mvc


【解决方案1】:

在 Jackson 中有对此的支持,尝试在支持类中指定一个包含具体类型信息的属性:

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

在 JSON 上,指定具体类型:

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

【讨论】:

    猜你喜欢
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 2012-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-13
    • 1970-01-01
    相关资源
    最近更新 更多