Search code examples
javaspringjspspring-annotationsspring-4

reading properties file in jsp using annotation spring 4


I need to do this, with annotation, withouth using xml file.

< bean id="placeholderConfig"       class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
        < property name="locations" >
            < list >
                < value >app.properties< / value >
            < / list >
        < / property >
< / bean >

And I need to call my property values in my jsp like ${test.name} (where test.name is configured in app.properties)

Now I do this

@PropertySource(value="app.properties", ignoreResourceNotFound=true)
...
@Bean(name="placeholderConfig")
    public static PropertySourcesPlaceholderConfigurer placeholderConfigurer(){
        PropertySourcesPlaceholderConfigurer cfg = new PropertySourcesPlaceholderConfigurer();
        cfg.setLocation(new ClassPathResource("app.properties"));
        cfg.setIgnoreUnresolvablePlaceholders(true);
        return cfg;
    }

In this way i can access whith

@Value("${test.name}")
    String name; //contain value of test.name configured in app.properties

But if i do ${test.name} in my jsp, this is not read. To let jsp read the value I have to do (in my java class)

@Value("${test.name}")
    String name;
...
model.addObject("name", name);

There is a way to access directly to my property from my jsp, whit ${test.name} code?


Solution

  • I found one way. I put this code in my java page, with my bean declarations

    @Bean(name="messageSource")
        public static ReloadableResourceBundleMessageSource messareSource(){
            ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource();
            messageSource.setBasename("/WEB-INF/app");
            return messageSource;
        }
    

    Put file app_it_IT.properties in WEB-INF folder

    test.name = test
    

    Finally I use this code in jsp page

    <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
    <spring:message code="test.name" var="propName"/ >
    ${propName}