=======================
有时候我们会把一些固定的参数写在配置文件里,所以获取资源的这些方式要知道
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
test02();
}
//相对规范的获取资源文件方法2
private void test03() throws IOException
{
//创建属性对象
Properties proper1=new Properties();
InputStream file1=getClass().getClassLoader().getResourceAsStream("../../file/_006_proper.properties");
proper1.load(file1);
String myname=proper1.getProperty("name");
System.out.println(myname);
}
private void test02() throws IOException
{
//properties配置文件或者其他资源文件都可以在WebContext里创建,不过一般是在src下面
//然后可以用ServletContext来获取
//获取全局唯一的Context对象
ServletContext serv1=super.getServletContext();
//如果参数填空,那么就是获取项目的绝对路径 d:\xxx\webapps/项目名/
//如果不为空,那么会和前面的路径拼接起来
String path1=serv1.getRealPath("file/_006_proper.properties");
System.out.println(path1);
//或者使用下面的直接直接获取流也可以
//InputStream input1=serv1.getResourceAsStream("file/_006_proper.properties");
Properties proper1=new Properties();
//FileInputStream不可能平白无故有一个目录,所以这里用../这样的是找不到路径的,因为它没有一个基础路径
//而重定向的时候,直接写response.sendRedirect("_006_successful.html"); 那是因为前面有response
//基础路径就是在项目路径
InputStream file1=new FileInputStream(path1);
proper1.load(file1);
String myname=proper1.getProperty("name");
System.out.println(myname);
}
//最常用方式获取资源文件
private void test01() throws IOException
{
//这里的properties配置文件是创建在src下面的,会复制一份在WEB-INF\classes里
//创建属性对象
Properties proper1=new Properties();
//我们发布到web工程里后,那么properties文件是在tomcat的webapps项目的WEB-INF的classes里的
InputStream file1=getClass().getClassLoader().getResourceAsStream("webConfig.properties");
proper1.load(file1);
String myname=proper1.getProperty("name");
System.out.println(myname);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
// TODO 自动生成的方法存根
super.doPost(req, resp);
}
扫描二维码关注公众号,回复:
3359740 查看本文章