Read properties file in Jsp

java properties file
java properties file

Reading a properties file in java is common, same way we can read the properties file in jsp is very simple but we do some common mistake when we read the properties file.

Flow the below step and see how easy is this.

  1. Properties file should be in class path.
java properties file
java properties file

2. Projects structure

properties file
read properties file in eclipse

3. Make a java class which will read the properties file and we can access that class from jsp. Basically it should be a class with static method which take String as parameter (key) and return the value from properties file. Mostly we put this method in a common util class.

 

ReadFromPropertiesFile.java

 

ReadFromPropertiesFile.java

package com.codewale.example;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadFromPropertiesFile {
///////////call this method from jsp
public static String getProperties(String key) throws IOException
{
InputStream inputStream=ReadFromPropertiesFile.class.getClassLoader().getResourceAsStream("codewale.properties");
Properties myproperties = new Properties();
/////////////load the properties file
myproperties.load(inputStream);
return myproperties.getProperty(key);
}
}

4. How to use in jsp page.

Index.jsp

<@ page import="com.codewale.example.ReadFromPropertiesFile>;
//Codewale read from properties file
<% out.println(ReadFromPropertiesFile.getProperties("test1")); out.println(ReadFromPropertiesFile.getProperties("test2")); %>


5. So we can write getProperties() method in a common class and call it from any jsp page.

 

Hope you have understand how to use properties file in a jsp file.

 

Download Code

Profile photo of Nirmal Dhara
About Nirmal Dhara 28 Articles
Java Developer

Be the first to comment

Leave a Reply

Your email address will not be published.


*