首页 > 代码库 > html转义字符

html转义字符

 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("&#039;"); 7             else if (c == ‘\"‘) 8                 out.append("&#034;"); 9             else if (c == ‘<‘)10                 out.append("&lt;");11             else if (c == ‘>‘)12                 out.append("&gt;");13             else if (c == ‘&‘)14                 out.append("&amp;");15             else if (c == ‘ ‘)16                 out.append("&nbsp;");17             else if (c == ‘\n‘)18                 out.append("<br/>");19             else20                 out.append(c);21         }22         return out.toString();23     }
View Code 1

需求:将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+"‘)");
View Code 2

用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();
View Code

2 从DB取出字符后,做转义处理

见:View Code 1

 

html转义字符