3

I am trying to create a Task Reader using Spring MVC. I have a 3 fields in Task: id, Description and dueDate.

Now on "Add Button" click, I am trying to send a Ajax call to the Spring controller. But I am not recieving the request at the server side.

Below is Ajax request code:

function doAjaxPost() {
    var id = $('#id').val();
    var desc = $('#description').val();
    var dueDate = $('#dueDate').val();
    var json = { "id" : id, "description" : desc, "dueDate": dueDate};
    $.ajax({
    type: "POST",
    contentType : "application/json",
    url: "/addTask",
    data : JSON.stringify(json),
    dataType : 'json',

    success: function(response){
    $('#info').html(response);
    },
    error: function(e){
    alert('Error: ' + e);
    console.log(e);
    }
    });
    }

And the controller code:

@RequestMapping(value = "/addTask", method = RequestMethod.POST)
    public @ResponseBody String addTask(@RequestBody Task task) {
        String returnText;
        System.out.println(task.getDescription() + " " + task.getDueDate());
        System.out.println(task);
        // taskList.add(task);
        returnText = "User has been added to the list. Total number of task are " + taskList.size();

        return returnText;
    }

I am getting the below error message in Chrome console.

The server refused this request because the request entity is in a format not supported by the requested resource for the requested method."

Can anybody point me to where am I making the mistake?

Update:

I am able to do it in a alternative way:

@RequestMapping(value = "/addTask" , method=RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
    public @ResponseBody String addTask(@RequestBody String task){
        Gson gson = new Gson();
        Task t = gson.fromJson(task, Task.class);
        taskList.add(t);
        ObjectMapper mapper = new ObjectMapper();
        String jsontastList = gson.toJson(taskList);
        return jsontastList;
    }

But I will still like to know the way where I don't need to explicitly convert json to Java object.

Nicky
  • 1,025
  • 3
  • 15
  • 29

3 Answers3

2

Set

consumes="application/json"
in
@RequestMapping
Chnage method to:
@RequestMapping(value = "/addTask", method = RequestMethod.POST,consumes="application/json")
 public @ResponseBody String addTask(@RequestBody Task task) {...}

Janis
  • 109
  • 1
  • 8
1

Did you configure message converter in Spring configuration? Like this:

<mvc:message-converters>  
    <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
        <property name="objectMapper">  
            <bean class="com.fasterxml.jackson.databind.ObjectMapper">
            </bean>  
        </property>  
    </bean>  
</mvc:message-converters>

And also you should add maven dependency like:

<dependency>  
    <groupId>com.fasterxml.jackson.core</groupId>  
    <artifactId>jackson-databind</artifactId>  
    <version>2.5.3</version>  
</dependency>
Blank
  • 12,308
  • 1
  • 14
  • 32
0

You are using @ResposeBody instead @RequestParam or you are not getting json correctly.

or to bind by @ResposeBody with multiple Json look at

  1. https://stackoverflow.com/a/37958883/5150781
  2. https://stackoverflow.com/a/21689084/5150781

Do like that ....

/*
 * Mapping for Demographics And Profiling Question Filter
 */
@RequestMapping (value = "/generalFilter")
public void ageFilteration(@RequestParam Map <String,String> filterParams,HttpServletRequest request,HttpServletResponse response) throws IOException
{
    //  System.out.println("Geographies in Controller :"+ filterParams.get("geographies"));
    List<FeasibilityBean> feasibilityList = feasibilityDao.getGeneralFeasibilityList(filterParams,request);
    //  System.out.println(" General Filter List Size:"+feasibilityList.size());
    response.getWriter().print(new Gson().toJsonTree(feasibilityList,new TypeToken<List<FeasibilityBean>>(){}.getType()));
}

}

Js Code

var ages='',ageCond='',genders='',genderCond='';

    $.ajax({
        type: "POST",
        url : url,
        data : {ages:ages,ageCond:ageCond,genders:genders,genderCond:genderCond},
        beforeSend: function() { 
            $(thisVar).find('i').addClass('fa-spin');
        },
        success : function(feasibilityJson){ 

        },
        error : function(data) {
            alert(data + "error");
        },
        complete:function(){  
            $(thisVar).find('i').removeClass('fa-spin');
        }
    }); 
Community
  • 1
  • 1
Zigri2612
  • 2,279
  • 21
  • 33