昨天给小伙伴们介绍了使用@JsonIgnore注解忽略JavaBean属性值的好处,有小伙伴说那若是不使用该注解呢,又该怎么写?其实我在前文有稍微提了一下,就是把setPassword设置为null值,不过没有展现具体的代码来进行对比,因此今天把不使用注解的方法给你们也顺便介绍一下,只是写起来稍微比一个注解麻烦了一点而已。 好了,很少说了,直接看代码。java
public class Hr {
private String hrname;
private String password;
public String getHrname() {
return hrname;
}
public void setHrname(String hrname) {
this.hrname = hrname == null ? null : hrname.trim();
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password == null ? null : password.trim();
}
//重载setPassword 方法,并设置为null
public void setPassword(){
this.password = null;
}
}
复制代码
public void onAuthenticationSuccess(HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
resp.setContentType("application/json;charset=utf-8");
PrintWriter out = resp.getWriter();
ObjectMapper om = new ObjectMapper();
Hr hr = (Hr)authentication.getPrincipal();//获取Hr对象
hr.setPassword();//获取被设置为null值的密码
String s = om.writeValueAsString(RespBean.ok("登陆成功!",hr));
out.write(s);
out.flush();
out.close();
}
复制代码
由于Authentication获取的是一个Object对象,要获取用户信息中的密码,咱们须要进行向下转型获取Hr对象而后再去获取密码,这样会变得麻烦了不少。因此强烈推荐使用@JsonIgnore注解!json