在servlet通过xml文件访问properties文件

来源:互联网 发布:淘宝上组装电脑 编辑:程序博客网 时间:2024/06/07 15:37

servlet代码

public void doPost(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {
ServletConfig cfg = this.getServletConfig();//读取web.xml文件
String filename = cfg.getInitParameter("config");//找到servlet中对应的参数名
String path = this.getServletContext().getRealPath("/");// 返回Servlet上下文路径
        path = path.substring(0, path.length() - 1);// 在Servlet上下文路径的最后包含一个"."号,所以这里将它去除
        path = path + filename;
        FileInputStream input = new FileInputStream(path);
        Properties prop= new Properties();
        prop.load(input);
        String name= prop.getProperty("name");// 获取name的值

web.xml代码
 <servlet>
    <description>This is the description of my J2EE component</description>
    <display-name>This is the display name of my J2EE component</display-name>
    <servlet-name>CheckUser</servlet-name>
    <servlet-class>CheckUser</servlet-class>
    <init-param>
    <param-name>config</param-name>
    <param-value>/WEB-INF/config.properties</param-value>
    </init-param>
  </servlet>

config.properties代码
name=admin
0 0
原创粉丝点击