Spring MVC controller adds request object to response

I am creating a JSON REST service with Spring 3.0.5, and my answer contains the object from my request , although I have not added it. I am using MappingJacksonJsonView and Jackson 1.6.4 to render the ModelAndView object in JSON.

Custom 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 queries 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'

Expected response

{"ok": "success"}

The answer I get is

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

Where and why is a custom object added to ModelAndView and how can I prevent this?

Possible Solution

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

It 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;
}
+3
2

, ajax. , ModelAndView. @ResponseBody, json.

public @ResponseBody Map registerUser(SimpleUser user){
     Map responseMap = new HashMap();
     if(registerUser(user)){
          responseMap.put("OK", "Success");
     } else {
          responseMap.put("OK", "Failure");
     }
     return responseMap;
}
+3

Spring 3.1.x modelKey org.springframework.web.servlet.view.json. MappingJacksonJsonView > * servlet.xml, :

Servlet.xml:

<bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView">
       <property name="modelKey" value="appResponse"/>
</bean>

:

@RequestMapping(value="/access") 
public @ResponseBody Model getAccess(Model model) {

  ...
  model.addAttribute("appResponse", responseDetails);
  ...

  return model;
}

modelKey , , , , / . , , (application/xml application/json).

+1

Source: https://habr.com/ru/post/1785162/


All Articles