Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring MVC Controller adds request object to response

I am building a JSON REST service with Spring 3.0.5 and my response contains the object from my request although I did not add it. I am using the MappingJacksonJsonView and Jackson 1.6.4 for rendering the ModelAndView object to JSON.

The User object is simple

public class SimpleUser {
    private String username;
    private String password;

    public String getUsername() { return username; }
    public void setUsername(String username) { this.username = username; }
    public String getPassword() { return password; }
    public void setPassword(String password) { this.password = password;
    }
}

One of the requests looks like this

@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register(SimpleUser user) {
    ModelAndView mav = new ModelAndView();
    mav.addObject("ok", "success");
    return mav;
}

Then I call the service with

curl 'http://localhost:8080/register?username=mike&password=mike'

The response I expect is

{"ok": "success"}

The response I get is

{"ok":"success","simpleUser":{"username":"mike","password":"mike"}}

Where and why is the user object added to the ModelAndView and how can I prevent that?

Possible solution

One way to work around this is to use Model instead of SimpleUser. This seems to work but it should be possible to use the business object.

This works:

@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register(Model model) {
    log.debug("register(%s,%s)", model.asMap().get("usernmae"), model.asMap().get("password"));
    ModelAndView mav = new ModelAndView();
    mav.addObject("ok", "success");
    return mav;
}
like image 281
magiconair Avatar asked May 07 '26 02:05

magiconair


1 Answers

It looks like you're trying to process a form submission and retrieve the result via ajax. If this is the case, you don't want to return a ModelAndView object. Use the @ResponseBody annotation to have Jackson represent your return object as a json object.

public @ResponseBody Map registerUser(SimpleUser user){
     Map responseMap = new HashMap();
     if(registerUser(user)){
          responseMap.put("OK", "Success");
     } else {
          responseMap.put("OK", "Failure");
     }
     return responseMap;
}
like image 110
EndlessLoop Avatar answered May 09 '26 15:05

EndlessLoop



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!