5

I'm looking for a way to evaluate a string as el when it is output in a JSP page. (i guess when it's toString() method is called under the hood???)

For example, in my page, if I do this:

<title>${bean.title}</title>

title will be a property of bean, which will return a string. I'd like to store other EL expressions in bean.title so they are evaluated.

So, if bean.title = "This is the ${param.pageType} page", obviously that would evaluate before it was written to the page.

Is there any way to do this?

Gary
  • 131
  • 1
  • 1
  • 4

1 Answers1

3

You're actually looking for the solution in the wrong direction. You should be using the JSTL fmt taglib for this. It supports parameterized messages as well. You should only change your code to store messages in an (internationalizable) .properties file instead of in the bean.

Assuming that you have the following key-value entry in the text.properties file which is placed in com.example.i18n package

title = This is the {0} page

then you can use it as follows

<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<fmt:setBundle basename="com.example.i18n.text" />
...
<title>
    <fmt:message key="title">
        <fmt:param value="${param.pageType}" />
    </fmt:message>
</title>

It adheres the rules of the MessageFormat API.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • hm - close. ResourceBundles work well for templated content, but in this case, I'm rendering content that comes from a CMS - well-structured content that contains arbitrary lists of things, etc. Also, since the naming of ResourceBundles is a convention based on their class name, I would be looking at a lot of ugly (slow?) reflection. I will look to see if there is way I can use MessageFormat. The first sticking point here is that MessageFormat relies on index/order rather than "keys". – Gary Apr 22 '11 at 18:09
  • You could also implement a custom `ResourceBundle` with a custom `Control` which you then put in the request scope using some `Filter` or `Servlet`. In the `Control` you can then load the bundle from the DB. You can find a basic example here http://stackoverflow.com/questions/4499732/design-question-regarding-java-ee-entity-with-multiple-language-support/4500633#4500633 (just ignore the JSF tags and on, use the aforementioned filter/servlet approach which puts them in request scope and then use `${bundle.title}` and on. – BalusC Apr 22 '11 at 18:15