栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

ServletContext读取属性文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

ServletContext读取属性文件

一、在src下创建资源文件

itcast.properties

Company = itcast
Address = Beijing
二、创建Servlet,根据相对路径读取资源文件 
public class TestServlet06 extends HttpServlet {

	private static final long serialVersionUID = -9049704689750672203L;

	
	public void doGet(HttpServletRequest request, 
	    HttpServletResponse response)throws ServletException, IOException {
		ServletContext context = this.getServletContext();
			PrintWriter out = response.getWriter();
			//获取相对路径中的输入流对象,第一个“/”代表web应用的根目录,
			//整个路径表示文件相对于web应用的相对路径,
			//src下的资源文件在tomcat启动时被复制到项目的WEB-INF/classes目录下
			InputStream in = context
				.getResourceAsStream("/WEB-INF/classes/itcast.properties");
			Properties pros = new Properties();
			pros.load(in);
			out.println("Company=" + pros.getProperty("Company") + "
"); out.println("Address=" + pros.getProperty("Address") + "
"); } }
 三、启动tomcat

http://localhost:8080/chapter03/TestServlet06

 四、根据绝对路径读取资源文件 
public void doGet(HttpServletRequest request, HttpServletResponse response)
                 throws ServletException, IOException {
	PrintWriter out = response.getWriter();                                                                       
	ServletContext context = this.getServletContext();                                                            
	// 获取文件绝对路径                                                                                                   
	String path = context.getRealPath("/WEB-INF/classes/itcast.properties");                                      
	FileInputStream in = new FileInputStream(path);                                                               
	Properties pros = new Properties();                                                                           
	pros.load(in); 
        out.println(path);                                                                                               
	out.println("Company=" + pros.getProperty("Company") + "
"); out.println("Address=" + pros.getProperty("Address") + "
"); }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/322996.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号