如何编码&解码使用decodeHTML&在Grails中编码AsHTML?

时间:2014-04-02 18:39:08

标签: grails groovy grails-2.0

我想了解编码和编码方式解码使用decodeHTML& encodeAsHTML

//解码 例子是

List symbols = ['!', '*', '/']
symbols.each { String symbol ->
    println symbol.decodeHTML()
}

它应该打印

!    // but it prints !
*   // but it prints *
/   // but it prints /

// encode示例

List symbols = ['!', '*', '/']
symbols.each { String symbol ->
    println symbol.encodeAsHTML()
}

它应该打印

'!'  // but it prints !
'*'  // but it prints *
'/'  // but it prints /

1 个答案:

答案 0 :(得分:5)

escapeAsHtml最终在apache commons lang

中致电StringEscapeUtils.escapeHtml

正如它在该方法的文档中所述;

  

使用HTML实体转义字符串中的字符。

     

例如:

     

"bread" & "butter"

     

成为:"bread" & "butter"

     

支持所有已知的HTML 4.0实体,包括时髦的重音。注意   常用的撇号转义字符(')不是a   法律实体等不受支持。)

它不会将所有字符转换为其实体值,因此!*/之类的内容将保持原样。这是Groovy中的一个例子:

@Grab( 'commons-lang:commons-lang:2.6' )
import static org.apache.commons.lang.StringEscapeUtils.escapeHtml

'!@£$%^&*()_+€-={}[]:"|;\'\\<>?,./~'.each {
    println "$it -> ${escapeHtml( it )}"
}

打印:

! -> !
@ -> @
£ -> &pound;
$ -> $
% -> %
^ -> ^
& -> &amp;
* -> *
( -> (
) -> )
_ -> _
+ -> +
€ -> &euro;
- -> -
= -> =
{ -> {
} -> }
[ -> [
] -> ]
: -> :
" -> &quot;
| -> |
; -> ;
' -> '
\ -> \
< -> &lt;
> -> &gt;
? -> ?
, -> ,
. -> .
/ -> /
~ -> ~