JSP 的變量 null pointer 錯誤小記


當寫程式時常常會用到以下的方法,來存取一個傳來的變量

1
2
String username = request.getParameter("username");
String password = request.getParameter("password");

同時我也許會對這些變量進行一些相關的檢查,如

1
2
3
4
5
6
7
8
9
if (username.isEmpty()) {
//................
return;
}

if (!password.equals("1234")) {
//................
return;
}

但是這常常這都會出現一些 null pointer 的錯誤.那就必須要使用以下方法

1
2
if (username != null && username.isEmpty()) { }
if (password != null && !password.equals("1234")) { }

其實可以通過這種方法來解決?

1
2
if ("".equals(username)) { }
if ("1234".equals(password)) { }