在 ColdFusion 上使用 JSoup 在服务器端处理表单数据

Manipulating form data server-side with JSoup on ColdFusion

继我之前的问题 () 之后,我想在插入将内容操纵到数据库中。

这是从表单发送到服务器的示例:

<form>
   <div id="Description" contenteditable="true">
   <p>
      Terminator Genisys is an upcoming 2015 American 
      science fiction action film directed by Alan Taylor. 

      <img id="Img0" src="http://www.moviepics.com/terminator1.jpg" />
      <img id="Img1" src="http://www.moviepics.com/terminator2.jpg" />
      <img id="Img2" src="http://www.moviepics.com/terminator2.jpg" />

      You can find out more by <a href="http://www.imdb.com">clicking here</a>
   </p>
   </div>
</form>

这是我的 CFC 目前处理它的方式(基本思路):

<cfquery>
INSERT INTO MyTable (Value1, Description)
VALUES
(
   <cfif structkeyexists(ARGUMENTS.Value1)>
      <cfqueryparam value="#ARGUMENTS.Value1#" cf_sql_type="nvarchar" />
   <cfelse>
      NULL
   </cfif>

   ,
   <!--- 
    Before the below happens, I need to replace the src 
    attributes of the img tags of Arguments.Description 
   --->
   <cfif structkeyexists(ARGUMENTS.Description)>
       <cfqueryparam value="#ARGUMENTS.Description#" cf_sql_type="nvarchar" />
   <cfelse>
       NULL
   </cfif>
)
</cfquery>

我知道 <div> 不是表单元素,但不用担心它仍然提交给 CF11,就好像它是使用 JQuery serialize() 技巧的表单元素一样。

当 CF11 处理这个表单时,它获取 ARGUMENTS.Description 中的数据。我想做的是解析这个参数的内容,找到 <img> 标签,并提取出 src 属性。

然后我将进行更多处理,但最终我需要用 CF11 在服务器端创建的不同值替换每个 img 标记中的 src 值.只有这样我才能将表单值插入数据库。

JSoup 可以协助完成此类任务吗?感觉就像一个简单的查找和替换任务,但我不知道如何去做。

首先,您的标记有误,图片标签的 src 属性没有右引号。确保在尝试使用此

之前修复该问题
<cfsavecontent variable="samform">
    <form>
    <div id="Description" contenteditable="true">
    <p>Terminator Genisys is an upcoming 2015 American science fiction action film directed by Alan Taylor. 

    <img id="Img0" src="http://www.moviepics.com/terminator1.jpg" />
    <img id="Img1" src="http://www.moviepics.com/terminator2.jpg" />
    <img id="Img2" src="http://www.moviepics.com/terminator2.jpg" />

    You can find out more by <a href="http://www.imdb.com">clicking here</a></p>
    </div>
    </form>
</cfsavecontent>

<cfscript>
jsoup = CreateObject("java", "org.jsoup.Jsoup");
alterform = jsoup.parse(samform);

imgs = alterform.select("##Description img");


for (img in imgs) {
    img.attr("src", "betterthan#listlast(img.attr("src"),"/")#");
}

imgs[2].attr("src", "TheyShouldHaveStoppedAtT2.gif");

writeOutput('<textarea rows="10" cols="100">#samform#</textarea><br>');
writeOutput('<textarea rows="10" cols="100">#alterform#</textarea>');
</cfscript>

如果您熟悉 css 选择器或 jquery 选择器,jSoup 选择几乎是第二天性。

它的作用是循环遍历 #Description 中的每个 img# 必须加倍,因为 CF)。然后它将 url 更改为基于当前 url 的内容,然后为了演示,我用其他内容覆盖了第二个 img 的 src 并在 textareas 中输出 before/after。