0

我正在尝试检查我使用 request.getParameter 声明的字符串是否为空或空。

但是当我尝试执行此代码时,我不断收到错误消息:错误是 nullexception 错误。

<%
String name = request.getParameter("name");
String acctnum = request.getParameter("acctnum");
String pin = request.getParameter("pin");
String balance = request.getParameter("balance");
out.println(name+acctnum+pin+balance);
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/jsp", "root", "");

String sql = "Insert into users(name, account_numer, pin, balance) values('"+name+"',     '"+acctnum+"', '"+pin+"', '"+balance+"')";
Statement stmt = conn.createStatement();
stmt.execute(sql);

conn.close();
if(name != null){
response.sendRedirect("index.jsp");
}

} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
%>

我也试过 .equals("") 但无济于事。

我在这里做错了什么,我想检查字符串是空的还是空的,以防止它重定向到另一个页面。

谢谢

4

2 回答 2

2

我相信您在到达之前会遇到异常if(name != null)。您在初始化sql变量时正在使用参数。您是否希望null在执行此操作时出现字符串?

我认为您应该在执行任何与数据库相关的操作之前进行空检查:

if (nullChecksPassed) {
    Class.forName("");
    Connection conn = DriverManager.getConnection("");
    String sql = "";
    Statement stmt = conn.createStatement();
    stmt.execute(sql);
    conn.close();
}
if (name != null) {
    response.sendRedirect("index.jsp");
}
于 2013-02-25T07:38:03.370 回答
2

可能值得检查一下 Apache 的StringUtils类,更具体地说是isEmpty(String str)方法:

public static boolean isEmpty(String str) 检查字符串是否为空 ("") 或 null。

StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = false

注意:此方法在 Lang 2.0 版中有所更改。它不再修剪字符串。该功能在 isBlank() 中可用。

参数: str - 要检查的字符串,可以为 null

返回:如果 String 为空或 null,则返回 true

此外,您可能希望对 SQL 查询使用准备好的语句。您拥有的那个很容易发生 SQL 注入。

于 2013-02-25T07:39:11.200 回答