简体   繁体   English

使用Jackson框架的@RequestBody注释的Spring Boot ObjectMapper

[英]Spring Boot ObjectMapper for @RequestBody annotation using Jackson Framework

Hy guys. 大家好

I have some data, given by a jQuery DataTable, that I send to a Spring Controller using Ajax and the data elements. 我有一些由jQuery DataTable提供的数据,我使用Ajax和数据元素将它们发送到Spring Controller。 More specifically, the ajax function fragment is: 更具体地说,ajax函数片段为:

$.ajax({
                        url: "../todaydatarecover.json",
                        type: "post",
                        data: dataToSend,

As explained me in another post here on Stack, I used (cause the presence of "data") the RequestBody annotation in my controller: 正如我在Stack上的另一篇文章中所解释的那样,我在控制器中使用了RequestBody注释(由于存在“数据”):

@PostMapping(value="/todaydatarecover.json")


@ResponseBody
    public ModelAndView todayInfoAndIdRecover(ModelAndView model, HttpServletRequest request,
            @RequestBody TodayData todayData) throws IOException
    {   

and, always as explained me, I make a class that have the variables that are sent by ajax to controller; 并且,总是像我所解释的那样,我创建一个类,该类具有由ajax发送到控制器的变量; in method sign, you can se that her name is TodayData. 在方法符号中,您可以确定她的名字是TodayData。 This is the implementation: 这是实现:

public class TodayData 
{
    private long dateInBox;
    private String nameInBox;
    private String typeInBox;

<follow setters and getters>

Searching on the web, I found that an explicit setting for object mapper may be requested; 在网上搜索时,我发现可能需要对对象映射器进行显式设置。 so, I found for my configuration (Spring Boot and Jackson Framework, both on last version) this one: 因此,我发现自己的配置(Spring Boot和Jackson Framework,均在上一版本中)是:

@Bean
     public MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter() {
      MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
      jsonConverter.setObjectMapper(objectMapper);
      return jsonConverter;
     }

that is putted in the public class MvcConfiguration extends WebMvcConfigurerAdapter file. 放在public class MvcConfiguration extends WebMvcConfigurerAdapter文件。

The data are passed to Controller as an Object: 数据作为对象传递给Controller:

$('#eventsdatageneral').on('click', '.btn.btn-info', function(event) 
            {
                var today_date = new Date().getTime(); 
                var dataToSend = new Object();
                dataToSend.dateInBox= today_date;
                dataToSend.nameInBox = host_name;
                dataToSend.typeInBox = type_name;

The problem is that when I click on the button that must enable sending, I got a 404 error. 问题是,当我单击必须启用发送的按钮时, 出现了404错误。

The object seems well formatted; 该对象似乎格式正确; on console, I got this: 在控制台上,我得到了:

对象响应

And the parametr seems right: 参数似乎正确:

对象参数

I got no errors on Java console; 我在Java控制台上没有错误;

So, what I don't understand is if i wrong the Object Mapper configuration or depends on what I implements on my controller, or other. 所以,我不明白的是,如果我错了Object Mapper配置,还是取决于我在控制器或其他控制器上实现的功能。

You need to do some changes in your code 您需要对代码进行一些更改

  1. You need to create JSON object as below in order to bind it with your Java POJO class TodayData : 您需要如下创建JSON对象,以便将其与Java POJO类TodayData

    $('#eventsdatageneral').on('click', '.btn.btn-info', function(event) { var today_date = new Date().getTime(); var dataToSend = {}; dataToSend["dateInBox"] = today_date; dataToSend["nameInBox"] = host_name; dataToSend["typeInBox"] = type_name;

  2. While sending your ajax request you need to use JSON.stringify function which will convert your javascript object to JSON. 在发送ajax请求时,您需要使用JSON.stringify函数,该函数会将您的JavaScript对象转换为JSON。

    $.ajax({ url: "../todaydatarecover.json", type: "post", data: JSON.stringify(dataToSend),

  3. Also as alfcope mentioned, ModelAndView and @ResponseBody shouldn't be used together, because when we use @ResponseBody on a method, we are saying that we do not want a view to be produced and the object will be returned as part of your response body. 同样如alfcope所述,不应将ModelAndView@ResponseBody一起使用,因为当我们在方法上使用@ResponseBody时,是说我们不希望生成视图,并且对象将作为响应的一部分返回身体。

  4. Check the url-pattern in configurations you've done for this application, or correct the url which you are sending as .json . 检查您为该应用程序完成的配置中的url-pattern ,或更正以.json形式发送的url。

You are using @RequestBody what means your controller is expecting a payload, so you need to serialise your JavaScript object using JSON.stringify before sending it, otherwise it is going to be sent as url form enconded. 您正在使用@RequestBody这意味着您的控制器需要有效负载,因此您需要在发送之前使用JSON.stringify序列化JavaScript对象,否则它将按照规定的url形式发送。

$.ajax({
  url: "../todaydatarecover.json",
  type: "post",
  data: JSON.stringify(dataToSend),
  ...
});

Also, your request mapping looks wrong. 另外,您的请求映射看起来不正确。 You are returning a ModelAndView but using @ResponseBody . 您将返回ModelAndView但使用@ResponseBody They should not be used together and it does not make sense return a ModelAndView to an ajax request. 不应将它们一起使用,并且将ModelAndView返回给ajax请求是没有意义的。

I suggest you to remove extensions ( .json ) from your request mappings. 我建议您从请求映射中删除扩展名( .json )。 It should be only: 只能是:

@PostMapping(value="/todaydatarecover")

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

相关问题 如何在 Spring 引导中为 Camel 配置 Jackson ObjectMapper - How to configure Jackson ObjectMapper for Camel in Spring Boot 使用 Jackson Objectmapper 配置的 Spring boot in Hibernate - Use Jackson Objectmapper configured by Spring boot in Hibernate Spring Boot 测试:使用 Jackson ObjectMapper 将模型转换为 JSON 字符串时 UserControllerTest 失败 - Spring Boot Test: UserControllerTest Fails When Using Jackson ObjectMapper To Convert Model To JSON String 使用 Spring Boot 和 Jackson ObjectMapper 时 OffsetDateTime 属性的 JSON 序列化差异 - Difference in JSON Serialization of OffsetDateTime Attribute when using Spring Boot and Jackson ObjectMapper 在使用@Requestbody注释在Spring Boot中进行处理之前,如何在数据库或日志文件中记录JSON或XML请求 - How to log JSON or XML request in a database or log file before processing in Spring boot using @Requestbody annotation Spring中Jackson ObjectMapper的生命周期 - Lifecycle of Jackson ObjectMapper in Spring Spring 注解缺少 requestBody - Spring Annotation missing requestBody Web服务使用Spring Boot支持RequestBody或RequestParam - Webservice supporting RequestBody or RequestParam using spring boot 为什么 Spring 引导不使用自定义 ObjectMapper bean? - Why Spring Boot not using custom ObjectMapper bean? 使用Jackson ObjectMapper进行序列化 - Serialize using Jackson ObjectMapper
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM