接上一篇。

2.3.4 利用ServletContext对象读取资源文件

比如我们要读取web项目中的配置文件。

项目目录结构如下:

使用ServletContext对象读取资源文件的示例代码如下:

package MyServletDemo;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ServletContextDemo6 extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8");
response.setHeader("content-type","text/html;charset=UTF-8");
//读取src目录下的properties配置文件
readSrcDirPropCfgFile(response);
response.getWriter().println("<hr/>");
//readWebRootDirPropCfgFile(response);//读取WebRoot目录下的properties配置文件
response.getWriter().println("<hr/>");
readPropCfgFile(response);//读取src目录下的db.config包中的db3.properties配置文件
response.getWriter().println("<hr/>");
readPropCfgFile2(response);//读取src目录下的gacl.servlet.study包中的db4.properties配置文件
}
private void readPropCfgFile2(HttpServletResponse response)
throws IOException {
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/MyServletDemo/db3.properties");
Properties prop = new Properties();
prop.load(in);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
response.getWriter().println("读取src目录下的MyServletDemo包中的db4.properties配置文件:");
response.getWriter().println(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
} private void readPropCfgFile(HttpServletResponse response)
throws FileNotFoundException, IOException {
//通过ServletContext获取web资源的绝对路径
String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db2.properties");
InputStream in = new FileInputStream(path);
Properties prop = new Properties();
prop.load(in);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
response.getWriter().println("读取src目录下的db.config包中的db3.properties配置文件:");
response.getWriter().println(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
}
private void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException {
/**
* 通过ServletContext对象读取src目录下的db1.properties配置文件
*/
InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db1.properties");
Properties prop = new Properties();
prop.load(in);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
response.getWriter().println("读取src目录下的db1.properties配置文件:");
response.getWriter().println(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doGet(request, response);
} }

上面的代码中,src目录都换成了WEB-INF/classes。这是因为当我们将项目以war的方式发布到tomcat上的时候,启动tomcat,tamcat会自动解压war包项目,之后我们在src目录下面所有的Java文件会编译成class字节码文件,然后存放到WEB-INF/classes目录,如果有其他文件也会相对于src的目录等级存放到相对于WEB-INF/classes相同目录等级下。所以src要替换成WEB-INF/classes。

void setContentType(String type)  设置发送到客户端的响应的内容类型,例如字符编码规范,text/html;charset=UTF-8。

setHeader(String name, String value)  设置具有给定名称和值的响应头。

运行之前还是在web.xml中进行servlet的配置。运行后输出结果:

2.3.5 使用类装载器读取资源文件

资源文件可以通过类加载器的方式加载到内存中,这种方式的好处是程序不用明确制定配置文件的具体所在目录。程序可以自动的在src目录下搜索该文件,并加载。即类加载器只能加载src目录下的资源文件,其它目录无法加载 ,此时/表示:/WEB-INF/classes/目录 。但是这种方法有一个弊端,通过类加载器加载进来的配置文件不能太大,否则会导致JVM内存溢出。 还有,类加载器加载类,类只加载一次,所以当该类被加载进内存后,如果此时有人修改了配置文件里面的配置信息,当再次访问该类时,得到的配置信息并没有改变,还是原来的,如果我们要得到更新后的配置信息就不能够用这种方法来加载配置信息。

使用类装载器读取资源文件的示例代码如下:

package MyServletDemo;

import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.Properties; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ServletContextDemo7 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setHeader("content-type","text/html;charset=UTF-8");
test1(response);
response.getWriter().println("<hr/>");
test2(response);
response.getWriter().println("<hr/>");
} /**
* 读取类路径下的资源文件
* @param response
* @throws IOException
*/
private void test1(HttpServletResponse response) throws IOException {
//获取到装载当前类的类装载器
ClassLoader loader = ServletContextDemo7.class.getClassLoader();
//用类装载器读取src目录下的db1.properties配置文件
InputStream in = loader.getResourceAsStream("db1.properties");
Properties prop = new Properties();
prop.load(in);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
response.getWriter().println("用类装载器读取src目录下的db1.properties配置文件:");
response.getWriter().println(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
} private void test2(HttpServletResponse response) throws IOException {
//获取到装载当前类的类装载器
ClassLoader loader = ServletContextDemo7.class.getClassLoader();
//用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件
InputStream in = loader.getResourceAsStream("MyServletDemo/db3.properties");
Properties prop = new Properties();
prop.load(in);
String driver = prop.getProperty("driver");
String url = prop.getProperty("url");
String username = prop.getProperty("username");
String password = prop.getProperty("password");
response.getWriter().println("用类装载器读取src目录下的gacl.servlet.study包中的db4.properties配置文件:");
response.getWriter().println(
MessageFormat.format(
"driver={0},url={1},username={2},password={3}",
driver,url, username, password));
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doGet(request, response);
}
}

在web.xml中配置servlet,运行后输出:

3. 在客户端缓存servlet的输出

对于不经常变化的数据,在servlet中可以为其设置合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能。

package MyServletDemo;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ServletDemo2 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "23623276172";
/**
* 设置数据合理的缓存时间值,以避免浏览器频繁向服务器发送请求,提升服务器的性能
* 这里是将数据的缓存时间设置为1天
*/
response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000);
response.getOutputStream().write(data.getBytes());
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { this.doGet(request, response);
} }

wx搜索“程序员考拉”,专注java领域,一个伴你成长的公众号!

servlet开发(四)之ServletContext的更多相关文章

  1. day05 Servlet 开发和 ServletConfig 与 ServletContext 对象

    day05 Servlet 开发和 ServletConfig 与 ServletContext 对象 1. Servlet 开发入门 - hello world 2. Servlet 的调用过程和生 ...

  2. Servlet开发(三)之ServletConfig,ServletContext

    1. ServletConfig Servlet是开发动态web的技术,而web.xml是Tomcat工程中最基础也最重要的配置文件,Tomcat启动项目的时候会加载并读取这个文件,其中web.xml ...

  3. JavaWeb学习总结第四篇--Servlet开发

    Servlet开发 用户在浏览器中输入一个网址并回车,浏览器会向服务器发送一个HTTP请求.服务器端程序接受这个请求,并对请求进行处理,然后发送一个回应.浏览器收到回应,再把回应的内容显示出来.这种请 ...

  4. javaweb学习之Servlet开发(二)

    javaweb学习总结(六)--Servlet开发(二) 一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个< ...

  5. java web 学习六(servlet开发2)

    一.ServletConfig讲解 1.1.配置Servlet初始化参数 在Servlet的配置文件web.xml中,可以使用一个或多个<init-param>标签为servlet配置一些 ...

  6. Servlet开发笔记(一)

    一.Servlet简介 Servlet是sun公司提供的一门用于开发动态web资源的技术. Sun公司在其API中提供了一个servlet接口,用户若想用发一个动态web资源(即开发一个Java程序向 ...

  7. Java第三阶段学习(十一、Servlet基础、servlet中的方法、servlet的配置、ServletContext对象)

    一.Servlet简介  1.什么是servlet: sun公司提供的一套规范(接口),用来处理客户端请求.响应给浏览器的动态资源.但servlet的实质就是java代码,通过java的API动态的向 ...

  8. Servlet开发-----基础及MVC设计模式

    一.Servlet介绍   Servlet本身只是普通的Java类,只有当容器为他创建了ServletConfig和ServletContext时才成为了一个Servlet:   Servlet简单的 ...

  9. 【JAVA EE企业级开发四步走完全攻略】

    本文是J2EE企业级开发四步走完全攻略索引,因内容比较广泛,涉及整个JAVA EE开发相关知识,这是一个长期的计划,单个发blog比较零散,所以整理此索引,决定以后每发一季JAVA EE blog后会 ...

  10. JavaWeb -- 服务器传递给Servlet的对象 -- ServletConfig, ServletContext,Request, Response

    1.  ServletConfig  有一些东西不合适在程序中写死,应该写在web.xml中,比如 文字怎么显示, 访问数据库名 和 密码, servlet要读取的配置文件 等等.. l在Servle ...

随机推荐

  1. 洛谷P3643 [APIO2016]划艇(组合数学)

    题面 传送门 题解 首先区间个数很少,我们考虑把所有区间离散化(这里要把所有的右端点变为\(B_i+1\)代表的开区间) 设\(f_{i,j}\)表示考虑到第\(i\)个学校且第\(i\)个学校必选, ...

  2. MySql数据库,对varchar类型字段str进行where str=0条件查询时,查询结果是什么

    在用MySQL查询数据的时候,遇到了一个奇怪的问题.用一个varchar类型的字符串str,作为条件与0比较时,会查str不为0的数据. 比如:SELECT id, idnumber from hr_ ...

  3. Chrome插件下载和安装方法

    http://jingyan.baidu.com/article/e4511cf35c2df92b845eafb3.html 扩展程序的下载方法   1 每个 Chrome 扩展程序 都有一个固定的 ...

  4. 性能分析工具VisualVM for eclipse安装过程总结

    Java VisualVM Java VisualVM is a tool that provides a visual interface for viewing detailed informat ...

  5. miniui中表单验证规则总结

    页面链接: http://www.miniui.com/demo/#src=form/rules.html 页面效果图: 页面代码: <!DOCTYPE html PUBLIC "-/ ...

  6. Oracle之索引

    简介 1.说明 1)索引是数据库对象之一,用于加快数据的检索,类似于书籍的索引.在数据库中索引可以减少数据库程序查询结果时需要读取的数据量,类似于在书籍中我们利用索引可以不用翻阅整本书即可找到想要的信 ...

  7. Git版本回退和撤销修改

    版本回退: 在实际工作中,我们会不断对文件进行修改,然后不断提交修改到版本库里,一旦你把文件改乱了,或者误删了文件,还可以从最近的一个commit恢复,然后继续工作,而不是把几个月的工作成果全部丢失. ...

  8. ps中的常用功能与技巧

    1.如何将多个png图片合成一个? 首先,打开ps,新建一个透明色画布,然后再将两张图片拖入(注意:回车拖入),然后再选中这三个图层,右键选择合并图层,最后快速导出为png即可. 2.如何快速找到ps ...

  9. ios 开发之旅

    你可能还在跟我一样傻傻的研究,怎么用visual studio 开发ios 里,哪就浪费时间吧!因为在安装 xmarin的时候,自动可以选择ios for Visual studio ,安装完也不能编 ...

  10. HttpSessionListener

    1 知识点