Question

I have a somewhat simplistic controller configured as thus:

@RequestMapping(value = "user/savearticle", method = RequestMethod.POST)
public @ResponseBody
Object saveArticle(@ModelAttribute("article")RawArticle rawArticle);

Using snippets of code taken from here, I made a test case for the controller that looks like this:

MvcResult resultActions =
         mockMvc.perform(MockMvcRequestBuilders.post("/user/savearticle")
         .contentType(MediaType.APPLICATION_FORM_URLENCODED)
         .content(convertObjectToForumUrlEncodedBytes(rawArticle)))
         .andReturn();

and I simply print out the result. In any case, the ModelAttribute "rawArticle" keeps ending up as null when it enters the controller's implementation, however when I use this:

MvcResult resultActions = mockMvc.perform(
        MockMvcRequestBuilders.post("/user/savearticle")
        .param("title", rawArticle.getTitle())
        .param("tags", rawArticle.getTags())
        .param("body", rawArticle.getBody())
        .param("author", rawArticle.getAuthor())).andReturn();

the mapping actually works like a charm. What I want though is that the first test be processed correctly as it seems so wrong that it's not being mapped as I thought it should be, similarly the controller is primarily being used by another program over the network using apache http (which somehow automatically passes a urlencoded form).

Do you guys have any idea where I could've made an error? I wouldn't mind posting snippets of my context configuration if you think you need it to evaluate the problem (or my pom for that matter, but just telling me what libraries I may have missed should be enough)

Update: I made a mistake of inserting the POJO into a session in test number 1, I simply removed it here. The question stands the same.

Était-ce utile?

La solution

The content is the content body of the request, you are using a content type which expects everything encoded in the URL not in the content body. Spring does data binding based on the request parameters if you want to use the content body you have to use @RequestBody instead of @ModelAttribute.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top