How to get properties in JSP files using spring mvc 3

前端 未结 3 1193
庸人自扰
庸人自扰 2021-02-04 08:49

I am very new to spring mvc 3 annotation based application. I have two properties files - WEB-INF\\resources\\general.properties, WEB-INF\\resources\\jdbc_config.properties

3条回答
  •  清歌不尽
    2021-02-04 09:18

    You need to distinguish between application properties (configuration) and localisation messages. Both use JAVA properties files, but they serve different purpose and are handled differently.

    Note: I am using Java based Spring configuration in the examples bellow. The configuration can be easily made in XML as well. Just check Spring's JavaDoc and reference documentation.


    Application Properties

    Application properties should be loaded as property sources within your application context. This can be done via @PropertySource annotation on your @Configuration class:

    @Configuration
    @PropertySource("classpath:default-config.properties")
    public class MyConfig  {
    
        @Bean
        public static PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer() {
            return new PropertySourcesPlaceholderConfigurer();
        }
    
    }
    

    Then you can inject properties using @Value annotation:

    @Value("${my.config.property}")
    private String myProperty;
    

    Localisation Messages

    Localisation messages is a little bit different story. Messages are loaded as resource bundles and a special resolution process is in place for getting correct translation message for a specified locale.

    In Spring, these messages are handled by MessageSources. You can define your own for example via ReloadableResourceBundleMessageSource:

    @Bean
    public MessageSource messageSource() {
        ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
        messageSource.setBasename("/WEB-INF/messages/messages");
        return messageSource;
    }
    

    You can access these messages from beans if you let Spring inject MessageSource:

    @Autowired
    private MessageSource messageSource;
    
    public void myMethod() {
        messageSource.getMessage("my.translation.code", null, LocaleContextHolder.getLocale());
    }
    

    And you can translate messages in your JSPs by using tag:

    
    

提交回复
热议问题