欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaWeb_ServletContext读取Web应用下的资源文件

程序员文章站 2022-03-19 16:04:35
咋...

 (1)新建JavaWeb项目 JavaWeb

(2)在src下新建ServletContext包->包下新建类TestServlet.java与文件info.properties

 info.properties内容

name=xiaoming
address=beijing

 TestServlet.java内容

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

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.ws.Response;
/**
 * 
 * @author zhangxinlin
 *	ServletContext读取文件内容
 */
public class TestServlet extends HttpServlet{
		@Override
		protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
			resp.setContentType("text/html;charset=utf-8");
			ServletContext context = this.getServletContext();
			PrintWriter out = resp.getWriter();
			//	相对路径获取输入流
			InputStream in=context.getResourceAsStream("/WEB-INF/classes/info.properties");
			//	绝对路径获取输入流
			String path=context.getRealPath("/WEB-INF/classes/info.properties");
			FileInputStream inPath= new FileInputStream(path);
			System.out.println(path);
			Properties pros = new Properties(); 
			pros.load(in);
			out.println("姓名:"+pros.getProperty("name")+"<br>");
			out.println("地址:"+pros.getProperty("address"));
		}

}

(3)在web.xml中添加TestServlet的映射

<servlet>
  	<servlet-name>TestServlet</servlet-name>
  	<servlet-class>ServletContext.TestServlet</servlet-class>
  </servlet>
  <servlet-mapping>
  	<servlet-name>TestServlet</servlet-name>
  	<url-pattern>/T</url-pattern>
  </servlet-mapping>

(4)访问结果

JavaWeb_ServletContext读取Web应用下的资源文件

 (5)项目结构

JavaWeb_ServletContext读取Web应用下的资源文件

本文地址:https://blog.csdn.net/weixin_45460315/article/details/111866435