jspjstl

How to get string from resource bundle and save as variable in JSP


I'm working on converting an old Struts 1.x application to Spring MVC and in some of the JSP pages, the bean:define tag is being used to get a string from a resource bundle, and is then used later in the page:

<bean:define id="example_title"><fmt:message bundle="${example_Labels}" key="example_field"/></bean:define>

then later:

title="<%=example_title%>"

I'm not sure what the equivalent JSTL (or if it even should be JSTL) tag should be in order to do away with the Struts tag, can anyone offer a suggestion? I've tried playing with JSTL set, and jsp:useBean, but either they're the wrong way to go or I'm implementing them improperly.

Thanks for any suggestions!


Solution

  • Use the var attribute of the fmt:message.

    <fmt:message bundle="${example_Labels}" key="example_field" var="example_title" />
    

    This basically exports the value associated with the key into a page scoped variable named example_title. You can print it later in the page the usual EL way:

    title="${example_title}"
    

    Or if you're still on pre-JSP-2.0 where EL in template text isn't supported (consider upgrading..), then use <c:out> to display it:

    title="<c:out value="${example_title}" />"