【JSP开发】用ServletContext读取资源文件

两种读取资源文件的方法。

db.properties文件中放了三个参数,分别是url、username和password信息。

测试代码:

package cn.edu;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Properties;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


//用ServletContext读取资源文件的方法
public class ServletDemo9 extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
        InputStream in =this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        
        //模板代码(采用传统FileInputStream直接读不好(相对路径),用ServletContext)
        Properties props = new Properties();//map
        props.load(in);
        
        String url=props.getProperty("url");
        String username=props.getProperty("username");
        String password=props.getProperty("password");
        
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
        
        System.out.println("方法二:");
		text2();
	}
	
	//通过ServletContext()的getRealPath得到资源的绝对路径后,再通过传统流读取资源文件  
	//采用ServletContext()利用传统FileInputStream方法读资源文件
	//这样得到的路径是真实路径(绝对路径),而不是上面说的相对路径
	public void text2() throws IOException{
		
		//这个方法可以拿到资源的名称
		String path=this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
		FileInputStream in =new FileInputStream(path);
        String filename=path.substring(path.lastIndexOf("\\")+1);
        
        System.out.println("资源文件名称为:"+filename);
		//System.out.println(path);
		//结果D:\apache-tomcat-6.0.24\webapps\day05\WEB-INF\classes\db.properties
		
		Properties props = new Properties();//map
        props.load(in);
        
        String url=props.getProperty("url");
        String username=props.getProperty("username");
        String password=props.getProperty("password");
        
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
	}




	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);


	}


}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值