标签:style blog http ar color os sp for on
1 public static String toHTMLString(String in) { 2 StringBuffer out = new StringBuffer(); 3 for (int i = 0; in != null && i < in.length(); i++) { 4 char c = in.charAt(i); 5 if (c == ‘\‘‘) 6 out.append("'"); 7 else if (c == ‘\"‘) 8 out.append("""); 9 else if (c == ‘<‘) 10 out.append("<"); 11 else if (c == ‘>‘) 12 out.append(">"); 13 else if (c == ‘&‘) 14 out.append("&"); 15 else if (c == ‘ ‘) 16 out.append(" "); 17 else if (c == ‘\n‘) 18 out.append("<br/>"); 19 else 20 out.append(c); 21 } 22 return out.toString(); 23 }
需求:将html输入框中的字符保存到DB中,再次打开html时将DB中的字符回填到html输入框中;
问题:
1 当输入框中只有一个单引号时,执行sql报错,应为sql文用单引号来表示起始;
2 当输入框填入双引号=html转义字符时,从DB回填到html时会破坏html标签;
处理:
1 不用Statement
1 stmt.executeUpdate("insert into tb_name (col1,col2,col2,col4) values (‘"+var1+"‘,‘"+var2+"‘,"+var3+",‘"+var4+"‘)");
用PreparedStatement来代替Statement
1 PreparedStatement pstmt = null; 2 perstmt = con.prepareStatement("insert into tb_name (col1,col2,col2,col4) values (?,?,?,?)"); 3 perstmt.setString(1,var1); 4 perstmt.setString(2,var2); 5 perstmt.setString(3,var3); 6 perstmt.setString(4,var4); 7 perstmt.executeUpdate(); 8 pstmt.close();
2 从DB取出字符后,做转义处理
标签:style blog http ar color os sp for on
原文地址:http://www.cnblogs.com/Im-hear/p/4141075.html