我正在尝试检查使用 request.getParameter 声明的字符串是否为 null 或空。
但是当我尝试执行此代码时,我不断收到错误: 错误是 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("") 但没有成功。
我在这里做错了什么,我想检查字符串是否为空或为空,以防止它重定向到另一个页面。
谢谢
最佳答案
也许值得查看 Apache 的 StringUtils
类,更具体地说是 isEmpty(String str)
方法:
public static boolean isEmpty(String str) Checks if a String is empty ("") or null.
StringUtils.isEmpty(null) = true
StringUtils.isEmpty("") = true
StringUtils.isEmpty(" ") = false
StringUtils.isEmpty("bob") = false
StringUtils.isEmpty(" bob ") = falseNOTE: This method changed in Lang version 2.0. It no longer trims the String. That functionality is available in isBlank().
Parameters: str - the String to check, may be null
Returns: true if the String is empty or null
此外,您可能希望对 SQL 查询使用准备好的语句。您所拥有的这个很容易受到 SQL 注入(inject)。
关于java - java中使用request.getParameter声明字符串时检查字符串是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15062088/