Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring @RequestParam arguments not being passed in POST method

I'm having a problem with Spring and a post request. I'm setting up an controller method for an Ajax call, see the method definition below

@RequestMapping(value = "add.page", method = RequestMethod.POST)
@ResponseBody
public Object createComment(
        @RequestParam(value = "uuid", required = false) String entityUuid,
        @RequestParam(value = "type", required = false) String entityType,
        @RequestParam(value = "text", required = false) String text,
        HttpServletResponse response) {
        ....

No matter what way I make the HTML call, the values for the @RequestParam parameters are always null. I have many other methods that looks like this, the main difference is that the others are GET methods, whereas this one is a POST. Is it not possible to use @RequestParam with a POST method?

I'm using Spring version 3.0.7.RELEASE - Does anyone know what the cause of the problem may be?


Ajax code:

$.ajax({
    type:'POST',
    url:"/comments/add.page",
    data:{
        uuid:"${param.uuid}",
        type:"${param.type}",
        text:text
    },
    success:function (data) {
        //
    }
});
like image 854
John Farrelly Avatar asked Dec 22 '12 21:12

John Farrelly


1 Answers

The problem turned out to be the way I was calling the method. My ajax code was passing all the parameters in the request body and not as request parameters, so that's why my @RequestParam parameters were all empty. I changed my ajax code to:

$.ajax({
    type: 'POST',
    url: "/comments/add.page?uuid=${param.uuid}&type=${param.type}",
    data: text,
    success: function (data) {
        //
    }
});

I also changed my controller method to take the text from the request body:

@RequestMapping(value = "add.page", method = RequestMethod.POST)
@ResponseBody
public Object createComment(
        @RequestParam(value = "uuid", required = false) String entityUuid,
        @RequestParam(value = "type", required = false) String entityType,
        @RequestBody String text,
        HttpServletResponse response) {

And now I'm getting the parameters as I expect.

like image 67
John Farrelly Avatar answered Oct 17 '22 15:10

John Farrelly