html逸出字元

來源:互聯網
上載者:User

標籤: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("&#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逸出字元

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.