0

Example: User.java

@Component
    public class User{
        public String name;
        public String email;



        public User() {
            super();
        }
        public User(String name, String email) {
            super();
            this.name = name;
            this.email = email;
        }
        public String getName() {
            return name;
        }
        public String getEmail() {
            return email;
        }
        public void setName(String name) {
            this.name = name;
        }
        public void setEmail(String email) {
            this.email = email;
        }



    }

HomeController.java

@Controller
public class HomeController {

    @Resource
    User user;

    @RequestMapping(value="/getUsers", method= RequestMethod.POST)
    public @ResponseBody User getUser(User user){
        return user;
    }
}

But user.getName() and user.getEmail() is null. User class is not initializing. Why? Even though I am sending user object at client side as

POST /spring/getUsers HTTP/1.1 Host: localhost:2015 Cache-Control: no-cache {"name":"vinod", "email":"[email protected]" }
3
  • Do you realize you're returning the user passed as argument to the method, and not the autowired user, which is completely useless? Also, if the user is in the request body, as JSON, the argument is supposed to be annotated with @RequestBody Commented Mar 2, 2015 at 19:46
  • You might have to go through basics of how autowiring works and Model attributes etc. Commented Mar 2, 2015 at 19:50
  • Please give example to the above code. Commented Mar 2, 2015 at 19:54

1 Answer 1

1

Here is a sample code. Please go through the documentation once to understand how requestBody annotation works etc.

@Controller
public class HomeController {

    @RequestMapping(value="/getUsers", method= RequestMethod.POST)
    public @ResponseBody User getUser(@RequestBody User user){
        return user;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.