在保存到数据库之前如何在JSP中escape-html? [英] How to escape-html in JSP before saving to database?

查看:333
本文介绍了在保存到数据库之前如何在JSP中escape-html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习JSP和Java,并写了一个(非常)简单的留言簿,以开始使用JSP。但是我想确保没有人可以使用CSS,所以我需要删除HTML代码,然后将其保存到mySQL数据库。我已经在这里搜索,发现

  PreparedStatement pStmt = conn.prepareStatement(INSERT INTO test VALUES(ID,?,?)); 

pStmt.setString(1,request.getParameter(sender));
pStmt.setString(2,request.getParameter(text));
pStmt。 executeUpdate();

那么这样做的正确方法是什么?

解决方案

简短的回答:看看 org.apache.commons.lang.StringEscapeUtils.escapeHtml()



更详细的答案:转义HTML是演示代码的工作,而不是数据库代码,如果由于某种原因,您希望在非Web环境中的某个时间点显示数据,例如经典GUI?你将不得不解开整个事情,否则会显示垃圾。



保存数据,并确保您在之前从用户中退出所有,否则您显示它(可以不是数字存储为数字,但是您可以想法)



如果您使用AJAX,您可以进一步了解,只能以JavaScript(或使用innerText)方式转义您的字符串。


I am learning JSP and Java at the moment and wrote a (very) simple guestbook to get started with JSP. But i want to ensure that noone can use CSS, so i need to strip the HTML code before saving it to my mySQL database. I already searched here and found the "

  PreparedStatement pStmt = conn.prepareStatement("INSERT INTO test VALUES (ID, ?, ?)");

  pStmt.setString(1, request.getParameter("sender"));
  pStmt.setString(2, request.getParameter("text"));
  pStmt.executeUpdate();

So what would be the proper way to do this ?

解决方案

Short answer: have a look at org.apache.commons.lang.StringEscapeUtils.escapeHtml().

More detailed answer: Escaping HTML is the job of the presentation code, not the database code. What if for some reason, you want to display you data at some point in a non-web environment, such as a classic GUI? You will have to unescape the whole thing, otherwise it will display total garbage.

Just save the data as it is and make sure you escape everything you get from the user right before you display it (ok, maybe not numbers stored as numbers, but you get the idea).

If you're using AJAX, you can take this even further and only escape your strings in JavaScript (or use innerText).

这篇关于在保存到数据库之前如何在JSP中escape-html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆