public static String toHTMLString(String in) {
StringBuffer out = new StringBuffer();
for (int i = 0; in != null && i < in.length(); i++) {
char c = in.charAt(i);
if (c == '\'')
out.append("'");
else if (c == '\"')
out.append(""");
else if (c == '<')
out.append("<");
else if (c == '>')
out.append(">");
else if (c == '&')
out.append("&");
else if (c == ' ')
out.append(" ");
else if (c == '\n')
out.append("<br/>");
else
out.append(c);
}
return out.toString();
}
1
需求:将html输入框中的字符保存到DB中,再次打开html时将DB中的字符回填到html输入框中;
问题:
1 当输入框中只有一个单引号时,执行sql报错,应为sql文用单引号来表示起始;
2 当输入框填入双引号=html转义字符时,从DB回填到html时会破坏html标签;
处理:
1 不用Statement
stmt.executeUpdate("insert into tb_name (col1,col2,col2,col4) values ('"+var1+"','"+var2+"',"+var3+",'"+var4+"')");
2
用PreparedStatement来代替Statement
PreparedStatement pstmt = null;
perstmt = con.prepareStatement("insert into tb_name (col1,col2,col2,col4) values (?,?,?,?)");
perstmt.setString(1,var1);
perstmt.setString(2,var2);
perstmt.setString(3,var3);
perstmt.setString(4,var4);
perstmt.executeUpdate();
pstmt.close();
2 从DB取出字符后,做转义处理
见:1