Servlet - Reasource loading

1. Load db3.properties

String path = this.getServletContext().getRealPath("/WEB-INF/classes/db/config/db3.properties");
InputStream in = new FileInputStream(path);
Properties prop = new Properties();
prop.load(in);

2. Load db4.properties

InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/gacl/servlet/study/db4.properties");
Properties prop = new Properties();
prop.load(in);
ClassLoader loader = ServletContextDemo.class.getClassLoader();
InputStream in = loader.getResourceAsStream("gacl/servlet/study/db4.properties");
Properties prop = new Properties();
prop.load(in);

3. Load db2.properties

InputStream in = this.getServletContext().getResourceAsStream("/db2.properties");
Properties prop = new Properties();
prop.load(in);

4. Load db1.properties

InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db1.properties");
Properties prop = new Properties();
prop.load(in);
ClassLoader loader = ServletContextDemo.class.getClassLoader();
InputStream in = loader.getResourceAsStream("db1.properties");
Properties prop = new Properties();
prop.load(in);

在客户端缓存Servlet的输出:

response.setDateHeader("expires",System.currentTimeMillis() + 24 * 3600 * 1000);
response.getOutputStream().write(data.getBytes());

多个Servlet通过ServletContext对象实现数据共享

ServletContext context = this.getServletConfig().getServletContext();
context.setAttribute("data", data);
ServletContext context = this.getServletContext();
String data = (String) context.getAttribute("data");

在web.xml文件中使用<context-param>标签配置WEB应用的初始化参数

<context-param>
   <param-name>url</param-name>
   <param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
ServletContext context = this.getServletContext();
String contextInitParam = context.getInitParameter("url");

用servletContext实现请求转发

ServletContext context = this.getServletContext();
RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");
rd.forward(request, response);

猜你喜欢

转载自www.cnblogs.com/iiiDragon/p/9881100.html