简体   繁体   中英

Reading property in a JSP

I am using Spring v4.1.7-RELEASE. I have gotten some complex back end code that loads the property file from the path.

I added a new property and I can see that I can read its value using @Value(${some-property})

@Value(value="${some-property}")
private String someProperty;

Now I want to pass this value to the JSP. The java code that has the above property do not have access to ServletContext, HttpServletRequest or HttpSession. In short our backed spit out JSON since they expose REST APIs.

How can I get this done?

You can read value from your property file directly on your jsp using spring expression language.

Add a util config like the one below and read it from your jsp.

<util:properties id="propertyConfig" location="classpath:conf/sample.properties"/>

<spring:eval expression="@propertyConfig['propertyname']" />

I realized that my JSP was not in the Servlet Context and hence it was not able to read the property file using the Spring tag library. To get it in the Servlet Context one needs to add the ViewResolver in your main-servlet.xml or whatever is the name of your servlet (DispatcherServlet) in the web.xml.

My work around was to directly read the property file in the JSP as follows:

<%

FileInputStream fis = new FileInputStream("/etc/path/some.properties");
Properties prop = new Properties();


try {
   prop.load(fis);
} 
catch (IOException e) {
    e.printStackTrace();
}

String someId = prop.getProperty("some.demo.id");
%>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM