Java後端避坑——不使用註解如何忽略掉JavaBean的屬性值

昨天給小夥伴們介紹了使用@JsonIgnore註解忽略JavaBean屬性值的好處,有小夥伴說那若是不使用該註解呢,又該怎麼寫?其實我在前文有稍微提了一下,就是把setPassword設置爲null值,不過沒有展現具體的代碼來進行對比,因此今天把不使用註解的方法給你們也順便介紹一下,只是寫起來稍微比一個註解麻煩了一點而已。 好了,很少說了,直接看代碼。java

先定義一個普通的Bean:

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

使用Postman獲得的測試結果以下:

聚沙成塔,滴水穿石!
相關文章
相關標籤/搜索