2017-03-13 54 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中,我们可以做到这一点转换器!! ?? –

相关问题