开发者

Scala/Java servlets: How to output < in the HTML code instead of &lt;

开发者 https://www.devze.com 2023-01-10 21:36 出处:网络
I have a servlet coded in Scala. I have some code like this in there: def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value}</BODY></HTML>

I have a servlet coded in Scala. I have some code like this in there:

def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value}</BODY></HTML>
def value = "Hello <BR/> World"

The corresponding HTML code generated for value 开发者_JAVA技巧is

Hello &lt;BR/&gt; World

How do I get it to generate the HTML code (shown below)?

Hello <BR/> World

Thanks in advance


If you don’t mind changing the type of value to xml.Elem, you can do

def value = <xml:group>Hello <BR/> World</xml:group>

Addition

In my opinion, you should type as much XML inline as possible. Only then will you have compile time validation of the input. All other solutions either give you a runtime exception at some point (say, you forgot some /) or might even break your XML layout.

However, if you really want to have an easy transform, you could do this:

class XmlString(str: String) {
  def assumeXML = xml.XML.loadString("<xml:group>" + str + "</xml:group>")
  def toUnparsedXML = new xml.Unparsed(str)
}
implicit def stringToXmlString(str: String) = new XmlString(str)

def value = "Hello <BR/> World"

and then (for some reason, it still shows the <xml:group> part; you could get rid of it with xml.NodeSeq.fromSeq(value.assumeXML.child) or similar)

def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value.assumeXML}</BODY></HTML>

or even (well, you would not need the implicit here, Unparsed(value) would do)

def message = <HTML><HEAD><TITLE>Test</TITLE></HEAD><BODY>{value.toUnparsedXML}</BODY></HTML>

The assumeXML method will fail with at runtime, if you provide invalid XML; toUnparsedXML will accept all input, even data that is potentially dangerous.

0

精彩评论

暂无评论...
验证码 换一张
取 消