Reputation: 1579
I'm trying to check if the string i declared using request.getParameter is null or empty.
But i keep getting an error when i tried doing this code: the error is nullexception error.
<%
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();
}
%>
i also tried .equals("") but to no avail.
What i am doing wrong here, i want to check whether the string is empty or null to prevent it form redirecting to another page.
Thank you
Upvotes: 0
Views: 7919
Reputation:
I believe you're getting the exception before you reach if(name != null)
. You are using the parameters while initializing the sql
variable. Are you expecting null
strings to be present while doing that?
I think you should have a null check before doing any DB related operation:
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");
}
Upvotes: 2
Reputation: 52185
It might be worth checking out Apache's StringUtils
class, more specifically the isEmpty(String str)
method:
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
Also, you might want to use prepared statements for your SQL queries. The one you have is prone to SQL injection.
Upvotes: 2