发布日期:2018-03-26
java,检查一个字符串是否不为null而且不空?+ 查看更多
java,检查一个字符串是否不为null而且不空?
+ 查看更多
发布日期:2018-03-26 10:49
分类:JAVA
浏览次数:141
在我的web应用程序中,我有一个搜索字段,里面有一些字符串和组合框。
所以,我发送两个参数到远程函数中。
所以,我发送两个参数到远程函数中。
我想检查用户输入不是null,不是空的。因此,我可以构造一个准确的查询。
public ArrayList findEmployees(String str, int dep) throws ClassNotFoundException, SQLException{ System.out.println("List IN"); ArrayList list = new ArrayList(); java.sql.Statement stmt; java.sql.ResultSet rs; Class.forName("com.mysql.jdbc.Driver"); String url = "jdbc:mysql://localhost:3306/general"; java.sql.Connection con = DriverManager.getConnection(url, "root", "1234"); System.out.println("URL: " + url); System.out.println("Connection: " + con); stmt = con.createStatement(); stmt = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY); String qry = "SELECT * FROM PERSON "; String werstr = "WHERE"; if(str!= null && str != "**here i want to check the 'str' is empty or not." ) { qry += werstr + " NAME LIKE '%"+str+"%'"; System.out.println(qry); werstr = "AND"; } if(dep != 0) { qry += werstr + "dept="+dep; } qry += ";"; System.out.println(qry); rs = stmt.executeQuery(qry); while (rs.next()) { Employee employee = new Employee(); String name = rs.getString(2); employee.setName(name); int id = rs.getInt(1); employee.setId(id); int dept = rs.getInt(4); employee.setDept(dept); int age = rs.getInt(3); employee.setAge(age); list.add(employee); } System.out.println("List Out"); return list; }做这件事的最好方法是什么?
isEmpty() 方法怎么样?
if(str != null && !str.isEmpty())一定要在这个以使用部分&&,因为如果第一部分失败,java将不会进行评估第二部分,从而保证如果str是null,你不会从结构str.isempty()中获得空指针异常。
当心,这只是从java SE 1.6起可用的。在以前的版本中你必须检查结构length() = = 0。
并且忽略空白:
if(str != null && !str.trim().isEmpty())包装在一个方便的功能:
public static boolean empty( final String s ) { // Null-safe, short-circuit evaluation. return s == null || s.trim().isEmpty(); } public static boolean empty( final String s ) { // Null-safe, short-circuit evaluation. return s == null || s.trim().isEmpty(); }成为:
if( !empty( str ) )