Java 对象'中的字段错误;用户';在字段上';用户配置文件';:拒绝值[3];
我已经下载了一个工作演示,在我运行它时,它工作得非常好。但是,当我刚刚开始使用注册页面的相同页面和功能时,我提交表单时,我遇到了错误:Java 对象'中的字段错误;用户';在字段上';用户配置文件';:拒绝值[3];,java,spring,jsp,spring-mvc,jpa,Java,Spring,Jsp,Spring Mvc,Jpa,我已经下载了一个工作演示,在我运行它时,它工作得非常好。但是,当我刚刚开始使用注册页面的相同页面和功能时,我提交表单时,我遇到了错误: [Field error in object 'user' on field 'userProfiles': rejected value [3]; codes [typeMismatch.user.userProfiles,typeMismatch.userProfiles,typeMismatch.java.util.Set,typeMismatch]; a
[Field error in object 'user' on field 'userProfiles': rejected value [3]; codes [typeMismatch.user.userProfiles,typeMismatch.userProfiles,typeMismatch.java.util.Set,typeMismatch]; arguments
[org.springframework.context.support.DefaultMessageSourceResolvable: codes [user.userProfiles,userProfiles]; arguments []; default message [userProfiles]]; default message
[Failed to convert property value of type 'java.lang.String' to required type 'java.util.Set' for property 'userProfiles'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type
[com.idev.tpt.model.UserProfile] for property 'userProfiles[0]': no matching editors or conversion strategy found]]
JSP文件:
<form:form id="userForm" action="newuser" modelAttribute="user">
<form:input type="hidden" path="id" id="id" />
<div class="form-group">
<form:input type="text" path="firstName" id="firstName" placeholder="First Name" class="form-control input-sm" />
</div>
<div class="form-group">
<form:input type="text" path="lastName" id="lastName" placeholder="Last Name" class="form-control input-sm" />
</div>
<div class="form-group">
<c:choose>
<c:when test="${edit}">
<form:input type="text" path="ssoId" id="ssoId" placeholder="SSO ID" class="form-control input-sm" disabled="true" />
</c:when>
<c:otherwise>
<form:input type="text" path="ssoId" id="ssoId" placeholder="SSO ID" class="form-control input-sm" />
<div class="has-error">
<form:errors path="ssoId" class="help-inline" />
</div>
</c:otherwise>
</c:choose>
</div>
<div class="form-group">
<form:input type="password" path="password" id="password" placeholder="password" class="form-control input-sm" />
<div class="has-error">
<form:errors path="password" class="help-inline" />
</div>
</div>
<div class="form-group">
<form:input type="text" path="email" id="email" placeholder="email" class="form-control input-sm" />
<div class="has-error">
<form:errors path="email" class="help-inline" />
</div>
</div>
<div class="form-group">
<form:select path="userProfiles" items="${roles}" multiple="true" itemValue="id" itemLabel="type" class="form-control input-sm" />
</div>
<!-- <div class="form-group">
<textarea class="form-control" id="prop_note" name="note" placeholder="Note" ></textarea>
</div> -->
<p class="demo-button btn-toolbar">
<span id="warningLbl" class="label label-warning" style="display: none;"></span>
<button id="propAddBtn" type="submit" class="btn btn-primary pull-right">Save</button>
<button id="propUpdateBtn" type="submit" class="btn btn-primary pull-right" style="display: none;">Update</button>
<button id="propClearBtn" type="button" class="btn btn-primary pull-right" style="display: none;">Clear</button>
</p>
<br>
</form:form>
@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("roles", userProfileService.findAll());
model.addAttribute("loggedinuser", getPrincipal());
return "registration";
}
/**
* This method will be called on form submission, handling POST request for
* saving user in database. It also validates the user input
*/
@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@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 "success";
return "registrationsuccess";
}
型号:
package com.websystique.springmvc.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import org.hibernate.validator.constraints.NotEmpty;
@SuppressWarnings("serial")
@Entity
@Table(name="APP_USER")
public class User implements Serializable{
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
@NotEmpty
@Column(name="SSO_ID", unique=true, nullable=false)
private String ssoId;
@NotEmpty
@Column(name="PASSWORD", nullable=false)
private String password;
@NotEmpty
@Column(name="FIRST_NAME", nullable=false)
private String firstName;
@NotEmpty
@Column(name="LAST_NAME", nullable=false)
private String lastName;
@NotEmpty
@Column(name="EMAIL", nullable=false)
private String email;
@NotEmpty
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "APP_USER_USER_PROFILE",
joinColumns = { @JoinColumn(name = "USER_ID") },
inverseJoinColumns = { @JoinColumn(name = "USER_PROFILE_ID") })
private Set<UserProfile> userProfiles = new HashSet<UserProfile>();
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getSsoId() {
return ssoId;
}
public void setSsoId(String ssoId) {
this.ssoId = ssoId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Set<UserProfile> getUserProfiles() {
return userProfiles;
}
public void setUserProfiles(Set<UserProfile> userProfiles) {
this.userProfiles = userProfiles;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((ssoId == null) ? 0 : ssoId.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof User))
return false;
User other = (User) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (ssoId == null) {
if (other.ssoId != null)
return false;
} else if (!ssoId.equals(other.ssoId))
return false;
return true;
}
/*
* DO-NOT-INCLUDE passwords in toString function.
* It is done here just for convenience purpose.
*/
@Override
public String toString() {
return "User [id=" + id + ", ssoId=" + ssoId + ", password=" + password
+ ", firstName=" + firstName + ", lastName=" + lastName
+ ", email=" + email + "]";
}
}
用户配置文件转换器
package com.websystique.springmvc.converter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.convert.converter.Converter;
import org.springframework.stereotype.Component;
import com.websystique.springmvc.model.UserProfile;
import com.websystique.springmvc.service.UserProfileService;
/**
* A converter class used in views to map id's to actual userProfile objects.
*/
@Component
public class RoleToUserProfileConverter implements Converter<Object, UserProfile>{
static final Logger logger = LoggerFactory.getLogger(RoleToUserProfileConverter.class);
@Autowired
UserProfileService userProfileService;
/**
* 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= userProfileService.findById(id);
logger.info("Profile : {}",profile);
return profile;
}
}
包com.websystique.springmvc.converter;
导入org.slf4j.Logger;
导入org.slf4j.LoggerFactory;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.core.convert.converter.converter;
导入org.springframework.stereotype.Component;
导入com.websystemque.springmvc.model.UserProfile;
导入com.websystique.springmvc.service.UserProfileService;
/**
*视图中用于将id映射到实际userProfile对象的转换器类。
*/
@组成部分
公共类RoleToUserProfileConverter实现转换器{
静态最终记录器Logger=LoggerFactory.getLogger(RoleToUserProfileConverter.class);
@自动连线
UserProfileService UserProfileService;
/**
*按Id获取用户配置文件
*@参见org.springframework.core.convert.converter.converter#convert(java.lang.Object)
*/
公共用户配置文件转换(对象元素){
整数id=Integer.parseInt((字符串)元素);
UserProfile profile=userProfileService.findById(id);
info(“Profile:{}”,Profile);
回报曲线;
}
}
已更新
还有一件事,当我使用model getter方法getUserProfiles()打印表单数据时,我得到的是空白数据,因此我认为它不会绑定所选的值。但是我打印的任何其他列都会完美绑定。在您的评论之后,我更新了我的回复: 问题可能出在JSP代码中。当应用程序调用控制器中的
saveUser()
方法时,将创建一个新的用户对象。但由于您在用户对象中键入了UserProfile
,因此应用程序必须知道如何从字符串创建UserProfile
(从
传递时)
您可以添加一个从字符串到UserProfile
的自定义转换器,或者使用Java标准类型创建一个UserDTO
类,并在控制器保存操作中使用它。代码类似于:
public String saveUser(@Valid UserDTO dto, ...) {
User user = createUserFromDTO(dto);
userService.saveUser(user);
}
如果定义了转换器,请检查是否在应用程序配置期间将其添加到
FormatterRegistry
另外,请确保使用JPA注释正确定义了
UserProfile
实体。谢谢您的回复。正如我在问题中提到的,我有一个工作演示,而且我使用了相同的文件副本粘贴到新项目,我面临一个问题。对于您的建议,我使用了与我在工作演示中使用的相同的用户配置文件,我没有更改任何内容。尝试根据您的评论完善我的答案。请查看编辑后的问题我添加了我的用户配置文件classI我认为问题不在JPA中。它在JSP端。尝试保存用户时是否显示错误?有关详细信息,请参阅我的更新答案。请共享完整的stacktrace。1。您还可以共享${roles}的值吗?2.能否尝试删除select标记的“多个”属性?3.如果仍然不起作用,请尝试使用path='userProfile[0]'而不使用'multiple'属性。您好,@sbsatter和NKR请查看讨论我已将所有详细信息分解到那里,并且我已通过再次集成演示解决了我的问题。现在我的演示运行得非常好。
public String saveUser(@Valid UserDTO dto, ...) {
User user = createUserFromDTO(dto);
userService.saveUser(user);
}