views:

89

answers:

3

I have a Java based web-application and a new requirement to allow Users to place variables into text fields that are replaced when a document or other output is produced. How have others gone about this?

I was thinking of having a pre-defined set of variables such as :
@BOOKING_NUMBER@
@INVOICE_NUMBER@

Then when a user enters some text they can specify a variable inline (select it from a modal or similar). For example:

"This is some text for Booking @BOOKING_NUMBER@ that is needed by me"

When producing some output (eg. PDF) that uses this text, I would do a regex and find all variables and replace them with the correct value:

"This is some text for Booking 10001 that is needed by me"

My initial thought was something like Freemarker but I think that is too complex for my Users and would require them to know my DataModel (eww).

Thanks for reading!

D.

A: 

I have used a similiar replacement token system before. I personally like something like.

[MYVALUE]

As it is easy for the user to type, and then I just use replacements to swap out the tokens for the real data.

Mitchel Sellers
Too complex. It sounds like reinventing the wheel when you already have MessageFormat that handles it.
Guido
But expecting a regular user to remember that {0} is name and that {1} is booking number is NOT practical, thus the need for something that can make more sense to the user, thus my recommendation.
Mitchel Sellers
That's a good point about the {0} naming convention.
belugabob
StringTemplate addresses the naming issues, but probably introduces other issues. Further investigation required.
belugabob
A: 

I would use Velocity or Freemarker and it support for it. As far as user you could show him those fields by relection of Class passed to the framework. That class would just have many fields. I think it will be much easier to maintain that ${obj.move}, however if you dont like prefix you could just push (by reflection) every field to the template engine, so you would be able to write ${move}.

01
+2  A: 

Have a look at java.text.MessageFormat - particularly the format method - as this is designed for exactly what you are looking for.

i.e.

MessageFormat.format("This is some text for booking {0} that is needed by me, for use with invoice {1}", bookingNumber, invoiceNumber);

You may even want to get the template text from a resource bundle, to allow for support of multiple languages, with the added ability to cope with the fact that {0} and {1} may appear in a different order in some languages.

UPDATE: I just read your original post properly, and noticed the comment about the PDF. This suggest that the template text is going to be significantly larger than a line or two.

In such cases, you may want to explore something like StringTemplate which seems better suited for this purpose - this comment is based solely on initial investigations, as I've not used it in anger.

belugabob