我有这样一个模型类,用于Hibernate:
@Entity
@Table(name = "user", catalog = "userdb")
@JsonIgnoreProperties(ignoreUnknown = true)
public class User implements java.io.Serializable {
private Integer userId;
private String userName;
private String emailId;
private String encryptedPwd;
private String createdBy;
private String updatedBy;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "UserId", unique = true, nullable = false)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
@Column(name = "UserName", length = 100)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
@Column(name = "EmailId", nullable = false, length = 45)
public String getEmailId() {
return this.emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
@Column(name = "EncryptedPwd", length = 100)
public String getEncryptedPwd() {
return this.encryptedPwd;
}
public void setEncryptedPwd(String encryptedPwd) {
this.encryptedPwd = encryptedPwd;
}
public void setCreatedBy(String createdBy) {
this.createdBy = createdBy;
}
@Column(name = "UpdatedBy", length = 100)
public String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(String updatedBy) {
this.updatedBy = updatedBy;
}
}
在Spring MVC的控制器中,使用DAO获取对象,并将其作为JSON对象返回。@Controller
public class UserController {
@Autowired
private UserService userService;
@RequestMapping(value = "/getUser/{userId}", method = RequestMethod.GET)
@ResponseBody
public User getUser(@PathVariable Integer userId) throws Exception {
User user = userService.get(userId);
user.setCreatedBy(null);
user.setUpdatedBy(null);
return user;
}
}
视图部分使用AngularJS完成,因此它将会获取如下的JSON数据
{
"userId" :2,
"userName" : "john",
"emailId" : "john@gmail.com",
"encryptedPwd" : "Co7Fwd1fXYk=",
"createdBy" : null,
"updatedBy" : null
}
如果我不想设置加密密码,我会将该字段设为空。
但我不希望这样做,我不想将所有字段都发送到客户端。如果我不想发送密码、更新者、创建者字段,那么我的结果 JSON 应该是这样的:
{
"userId" :2,
"userName" : "john",
"emailId" : "john@gmail.com"
}
我不想把来自其他数据库表的某些字段发送给客户端,因此它会根据已登录的用户而改变。我该怎么做?
希望您理解我的问题。
entityClass.setFieldToIgnore(null)
。Spring-MVC默认设置为在反序列化时忽略null值,或者您可以手动配置它。 - Andrew Mititi