【发布时间】:2012-01-13 20:18:04
【问题描述】:
故事
我有一个代表用户访问级别的选择控件。我正在寻找一种使其国际化的方法。标签应该从消息资源中加载,并且值应该按原样使用。我使用具有标签和值属性的简单 SelectOption 类在控制器中准备所有下拉列表。这样,我的选择在所有 jsp 中看起来都是一致的。
问题
我找到了一些示例,但它们是基于 jsp 中的逻辑。开发人员遍历他的标签并使用消息资源手动构造选项标签。虽然这可行,但必须有更好的方法。我还发现 Spring 3 将支持国际化选项标签的一些 cmets,但我找不到任何具体的内容。
控制器逻辑
Collection<SelectOption> optionList = new ArrayList<SelectOption>();
optionList.add(new SelectOption("-SELECT-", "-"));
optionList.add(new SelectOption("Administrator", "ADMIN"));
optionList.add(new SelectOption("Editor", "EDIT"));
bean.setFilterUserAccessLevelOptionList(optionList);
JSP 逻辑
<form:select path="filterUserAccessLevel" items="${bean.filterUserAccessLevelOptionList}" itemLabel="label" itemValue="value"/>
问题
- 我想以这种方式在我的控制器中添加选项: optionList.add(new SelectOption("userAccessLevelAdministratorLabel", "ADMIN"));并让 Spring 将 userAccessLevelAdministratorLabel 转换为消息资源中的值。这可能吗?
- 如果 Spring 3 不能为我做到这一点,如果不在 jsp 中手动构造选项标签,那如何实现呢?
=== 2012-01-15 ==================================== ===========================
仍在尝试使用 aweigold 的想法制定解决方案。
控制器
@Controller
public class UserController {
@Autowired
private UserService userService;
@Autowired
SelectOptionListBuilder listBuilder;
@RequestMapping("/userIndex/{pageNumber}")
public ModelAndView getUserList(@PathVariable Integer pageNumber, @ModelAttribute("userIndexBean") UserIndexBean phantomBean, Locale locale, Model model) {
UserIndexBean bean = new UserIndexBean();
// prepare filter form
Collection<SelectOption> optionList = listBuilder.getUserAccessLevelOptionList(true, SortOrder.NONE, locale);
bean.setFilterUserAccessLevelOptionList(optionList);
SelectOptionListBuilderImpl
@Component
public class SelectOptionListBuilderImpl implements SelectOptionListBuilder, MessageSourceAware {
private MessageSource messageSource;
@Override
public void setMessageSource(MessageSource messageSource) {
this.messageSource = messageSource;
}
@Override
public List<SelectOption> getUserAccessLevelOptionList(boolean addSelectPrompt, SortOrder sortOrder, Locale locale) {
List<SelectOption> optionList = new ArrayList<SelectOption>();
if(addSelectPrompt) {
optionList.add(new SelectOption(messageSource.getMessage("common.selectPromptLabel", null, locale), "-"));
}
消息源映射
<bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename" value="/WEB-INF/i18n/messages" />
<property name="defaultEncoding" value="UTF-8"/>
<property name="UseCodeAsDefaultMessage" value="true"/>
</bean>
例外
org.springframework.context.NoSuchMessageException: No message found under code 'common.selectPromptLabel' for locale 'en_CA'
【问题讨论】:
标签: spring select internationalization