在作先后端分离的时候,咱们须要经过JSON数据的传递来实现相应的业务功能,例如在作登陆接口的时候,咱们能够使用Spring Security安全框架进行认证登陆,将用户信息等数据保存到Authentication中,而后给前端返回相应的JSON数据,这些信息确定会包含用户帐号密码等一系列已经保存在数据库中用户的信息。前端
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();
String s = om.writeValueAsString(RespBean.ok("登陆成功!",authentication.getPrincipal()));
out.write(s);
out.flush();
out.close();
}
复制代码
这个时候就会涉及到一个问题,咱们没有必要将用户的密码信息也返回到前端去,由于那样会存在用户信息不安全。那咱们应该怎么办呢?一般咱们通常会想要把setPassword设置为null值,然返回的密码为空,这是一种方法。 不过还有一种更为简便的方法,就是在getPassword的方法上加上 @JsonIgnore,简洁又方便。java
@JsonIgnore//生成json时忽略这个字段
@Override
public String getPassword() {
return password;
}
复制代码
@JsonIgnore,这个注解的做用是JSON序列化时将Java bean中的一些属性忽略掉,须要注意的是序列化和反序列化都会受到影响。数据库
聚沙成塔,滴水穿石!json