2017-03-13 46 views
0

我有兩個數據模型的用戶和車:未能Object類型的值轉換爲所需類型的對象春

User.java:

@Entity 
@Table(name="APP_USER") 
public class User implements Serializable{ 

@Id @GeneratedValue(strategy=GenerationType.IDENTITY) 
private Integer id; 
...... 

@OneToMany(mappedBy="user",cascade=CascadeType.ALL) 
private Set<Car> cars = new HashSet<Car>(); 

Car.java:

@Entity 
public class Car implements Serializable { 

@Id 
@GeneratedValue(strategy=GenerationType.IDENTITY) 
private int id ; 
..... 

@ManyToOne(optional=false) 
@JoinColumn(name="user_fk") 
private User user; 

在控制器中,我想添加一個新用戶,所以

AppController.java:

@Controller 
@RequestMapping("/") 
@SessionAttributes("roles") 
public class AppController { 

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET) 
public String newUser(ModelMap model) { 
    User user = new User(); 
    model.addAttribute("user", user); 
    model.addAttribute("edit", false); 
    model.addAttribute("loggedinuser", getPrincipal()); 
    return "registration"; 
} 

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST) 
public String saveUser(@ModelAttribute @Valid User user, BindingResult result, 
     ModelMap model) { 

    if (result.hasErrors()) { 
     return "registration"; 
    } 

    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){ 
     FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault())); 
     result.addError(ssoError); 
     return "registration"; 
    } 

    userService.saveUser(user); 
    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully"); 
    model.addAttribute("loggedinuser", getPrincipal()); 
    return "registrationsuccess"; 
} 

另外,我創建了一個名爲StringToUser類(實現轉換器,所以我可以添加包含用戶新車)

StringtoUser.java:

@Autowired 
UserService userService ; 

@Override 
public User convert(Object element) { 
    Integer id = Integer.parseInt((String)element); 
    User user = userService.findById(id); 
    return user; 
} 

在我添加StringToUser類之前,AppController.java和saveUser方法正常工作。但是在創建d StringToUser類,我得到了saveUser方法錯誤

The error is : WARNING: Failed to bind request element: org.springframework.beans.TypeMismatchException: Failed to convert value of type [com.websystique.springmvc.model.User] to required type [com.websystique.springmvc.model.User]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [com.websystique.springmvc.model.User] to type [@org.springframework.web.bind.annotation.ModelAttribute @javax.validation.Valid com.websystique.springmvc.model.User] for value 'User [id=null, ssoId=alaa, password=alaa1991, firstName=, lastName=, email=, userProfiles=null, accounts=null, userDocuments=[], cars=[], documents=[]]'; nested exception is java.lang.ClassCastException: com.websystique.springmvc.model.User cannot be cast to java.lang.String 

編輯:

錯誤:

WARNING: Failed to bind request element: org.springframework.beans.TypeMismatchException: Failed to convert value of type [com.websystique.springmvc.model.User] to required type [com.websystique.springmvc.model.User]; nested exception is org.springframework.core.convert.ConversionFailedException: Failed to convert from type [com.websystique.springmvc.model.User] to type [@org.springframework.web.bind.annotation.ModelAttribute @javax.validation.Valid com.websystique.springmvc.model.User] for value 'User [id=null, ssoId=alaa, password=alaa1991, firstName=, lastName=, email=, userProfiles=null, accounts=null, userDocuments=[], cars=[], documents=[]]'; nested exception is java.lang.NullPointerException 
+0

看來您的convert類正在接收對User類的引用,而不是您需要的String表示。你試過替換:Integer id = Integer.parseInt((String)element); for:Integer id =((User)element).getId(); –

+0

我剛試過你的例子,我遇到了同樣的問題! –

+0

你能提供完整的錯誤堆棧跟蹤嗎?你確定它在轉換器類中錯誤嗎? –

回答

0

你並不需要使用一個轉換器,彈簧本身格式化形式進入用戶類。

如果你調試你的轉換器類,你會注意到你沒有收到一個字符串作爲參數,你會收到一個類用戶的實例的引用。所以你正在將一個用戶轉換爲一個沒有意義的用戶。

@Override 
    public User convert(Object element) { 
     if (element == null) { 
      return null; 
     } 
     Integer id = ((User)element).getId(); 
     User user = userService.findById(id); 
     return user; 
    } 

現在,因爲你要創建一個新的用戶,你的形式不設置和ID,因此您提供userService空。您的服務失敗,您的轉換器無法顯示您的錯誤。

簡單的解決方案就是將其刪除。

我知道你添加了角色轉換器,因爲表單向你發送了一個整數列表,不能被spring解析成一個Set。我強烈建議您將Command對象作爲模型的中介,這樣可以避免使用Set。

但是,如果你需要實現一個轉換器,我建議修改如下:

@Component 
public class RoleToUserProfileConverter implements Converter<Object, UserProfile>{ 

    static final Logger logger = LoggerFactory.getLogger(RoleToUserProfileConverter.class); 

    @Autowired 
    private UserProfileService userProfileService; 


    private HashMap<Integer, UserProfile> userProfiles; 

    /** 
    * Gets UserProfile by Id 
    * @see org.springframework.core.convert.converter.Converter#convert(java.lang.Object) 
    */ 
    public UserProfile convert(Object element) { 
     Integer id = Integer.parseInt((String)element); 
     UserProfile profile = findUserProfile(id); 
     logger.info("Profile : {}",profile); 
     return profile; 
    } 

    private UserProfile findUserProfile(Integer id) { 
     //First time loading profiles 
     if(userProfiles == null) { 
      userProfiles = new HashMap<>(); 
      List<UserProfile> userProfileList = userProfileService.findAll(); 
      for(UserProfile userProfile: userProfileList) { 
       userProfiles.put(userProfile.getId(), userProfile); 
      } 
     } 
     if(userProfiles.containsKey(id)) { 
      return userProfiles.get(id); 
     } 
     return null; 
    } 

} 

在這個例子中,我使用HashMap來保存它應該改變減去所有的UserProfiles,那麼那些被加載只是第一次和retrived。

您可以通過檢查您正在查找的標識是否位於散列中的otherwhise查詢數據庫並將其存儲,從而根據需要加載新的UserProfiles來改進它。

+0

Hello @ Cristian,我只是刪除了StringtoUser類,並添加了findUserProfile方法,我有同樣的錯誤,用戶fom工作正常,但汽車形式不是,錯誤是一樣的: –

+0

org.apache.jasper.JasperException:java.lang.IllegalStateException :BindingResult和bean名稱'user'的普通目標對象都不可用作爲請求屬性 –

+0

Cristian,我可以創建這些類而不使用轉換器來角色和用戶嗎?我是新的使用spring,但在JSF中,我們可以做到這一點轉換器!! ?? –

相關問題