2015-03-02 86 views
0

實施例:User.java爲什麼對象在spring mvc中沒有初始化?

@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; 
    } 
} 

但是user.getName()和user.getEmail()爲空。用戶類未初始化。爲什麼?即使我在客戶端發送用戶對象,因爲

POST /spring/getUsers HTTP/1.1 Host: localhost:2015 Cache-Control: no-cache {"name":"vinod", "email":"[email protected]" } 
+0

註釋如何requestBody作品等你意識到你作爲參數傳遞的用戶返回方法,而不是自動裝配Autowired用戶,這是完全無用的?另外,如果用戶在請求正文中,作爲JSON,參數應該用'@ RequestBody'註釋 – 2015-03-02 19:46:42

+0

您可能需要了解自動裝配工作原理和模型屬性等基本知識。 – minion 2015-03-02 19:50:58

+0

請給出上述示例碼。 – 2015-03-02 19:54:04

回答

1

以下是示例代碼。請通過文檔一下子明白

@Controller 
public class HomeController { 

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