NewYork NewYork NewYork

How to use struts2 s:set variable inside s:select tag for list values?

285 Views Asked by At

I want to use a s:set variable inside s:select:

<s:set var="cityNY">NewYork</s:set>

<s:select name="cities" list="#{'%{#cityNY}':'%{#cityNY}'}" required="true" />

the above just prints the same value in my page - %{#cityNY}

want to display the value if s:set variable in options of s:select tag

1

There are 1 best solutions below

5
Roman C On

You need to put a context variable directly to OGNL expression without %{}. It will instantiate a map.

<s:select name="cities" list="#{#cityNY:#cityNY}" required="true" />

The list attribute value can contain an OGNL expression. It is used by default to parse value for OGNL without explicit %{}. Subexpressions can be referenced directly inside OGNL expression. #{exp1:exp2} is an OGNL expression to instantiate a Map. It has subexpressions inside. Each subexpressions should return a single value which is not a collection. Because they used to create a key/value pair for the map.

If you use the same subexpressions then better to instantiate a List with the following code

<s:select name="cities" list="{#cityNY}" required="true" />

It will generate a HTML <select> tag with one <option> with the same value and text.

If you need more options then you should add values to the OGNL expression with the comma.

The reference docs you can find in my answer to OGNL/Struts2 JSP assigning bean to an object.