2015-03-02 116 views
0

我試圖從客戶端發送對象到服務器。下面是使用spring mvc的控制器。請求處理失敗;嵌套的異常是org.springframework.beans.BeanInstantiationException

@Controller 
public class HomeController { 

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



    } 

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

在客戶端,我在郵寄對象這樣 http://localhost:2015/spring/getUsers

POST /spring/getUsers HTTP/1.1 
Host: localhost:2015 
Cache-Control: no-cache 

{"name":"vinod", "email":"[email protected]" } 

但我喜歡這個

HTTP Status 500 - Request processing failed; nested exception is org.springframework.beans.BeanInstantiationException: Could not instantiate bean class [com.vinod.spring.HomeController$User]: No default constructor found; nested exception is java.lang.NoSuchMethodException: com.vinod.spring.HomeController$User.<init>() 

回答

0

得到錯誤在服務器端儘量使重構你的用戶類到另一個文件,並使用@Resource註釋將其引用到您的控制器中。也許這個異常是因爲User類嵌套而拋出的。

實施例: 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; 
    } 
} 
+0

請給例子。如何使用@Resource註釋? – Ramesh 2015-03-02 16:46:09

+0

@Ramesh,我用例子更新了答案。 – marcelobrgomes 2015-03-02 18:32:15

+0

但是user.getName()和user.getEmail()爲空。用戶類未初始化。爲什麼?即使我在客戶端發送用戶對象爲POST/spring/getUsers HTTP/1.1主機:localhost:2015 緩存控制:no-cache {「name」:「vinod」,「email」:「vinod @ gmaol.com「} – Ramesh 2015-03-02 19:06:39

相關問題