Spring MVC best way to populate drop down list - p

2020-07-18 23:04发布

问题:

I want to populate a drop down list and I do not want to keep going to the database. I was thinking to have my country list or language list in a properties file. That way I could read it in, and then assign that to a variable. I could then return that through the ModelAndView type.

Is this a good approach? I am not sure how else to store static data. I do not want to keep it in a class because it will be harder to update it if there needs to be a change.

回答1:

got an answer! If I got a list of countries or languages, anything static, I can have this in my spring context file:

<util:map id="countryList" map-class="java.util.HashMap">
    <entry key="CA" value="Canada"/>
    <entry key="US" value="United States"/>
    <entry key="PK" value="Pakistan"/>
    <entry key="UE" value="UAE"/>
</util:map>

etc.

I would inject country list in my ModelAndView (or I think you can even access it directly without putting it in ModelAndView cuz it's in the global Spring context)

and then render ${countryList} in my jsp do -
<form:select path="country">
<form:option value="NONE" label="--- Select ---"/>
<form:options items="${countryList}" />
</form:select>

The options field should automatically render. That is the gyst of of, I am going to try this now!! Thanks!!



回答2:

You could as well store this data in the database and use a cache for example like ehCache. As they are stored in a database they could be updated easily and the cache would avoid to go to the database every time you need this information.