java - Servlet init and Class -
i have programm servlet :
@webservlet("/controler") public class controler extends httpservlet { }
i need use property file : file.properties
in program. load it, have class :
public class proploader { private final static string m_propertyfilename = "file.properties"; public static string getproperty(string a_key){ string l_value = ""; properties l_properties = new properties(); fileinputstream l_input; try { l_input = new fileinputstream(m_propertyfilename); // file not found exception l_properties.load(l_input); l_value = l_properties.getproperty(a_key); l_input.close(); } catch (exception e) { e.printstacktrace(); } return l_value; } }
my property file in webcontent folder, , can access :
string path = getservletcontext().getrealpath("/file.properties");
but can't call theses methods in class servlet...
how can access property file in proploader class ?
if want read file within webapp structure, should use servletcontext.getresourceasstream()
. , of course, since load webapp, need reference object representing webapp: servletcontext. can such reference overriding init()
in servlet, calling getservletconfig().getservletcontext()
, , pass servlet context method loading file:
@webservlet("/controler") public class controler extends httpservlet { private properties properties; @override public void init() { properties = proploader.load(getservletconfig().getservletcontext()); } } public class proploader { private final static string file_path = "/file.properties"; public static properties load(servletcontext context) { properties properties = new properties(); properties.load(context.getresourceasstream(file_path)); return properties; } }
note exceptions must handled.
another solution put file under web-inf/classes
in deployed webapp, , use classloader load file: getclass().getresourceasstream("/file.properties")
. way, don't need reference servletcontext
.
Comments
Post a Comment