1.ServletConfig 詳解
1.1、概念與用法
共有四個 API:
- getInitParameter(String name): 擷取指定參數名的初始化參數
- getInitParameterNames(): 擷取參數名組成的 Enumeration 對象.
- getServletName
- getServletContext
ServletConfig 封裝了 Serlvet 的配置資訊, 并且可以擷取 ServletContext 對象
在Servlet的配置檔案web.xml中,可以使用一個或多個标簽為servlet配置一些初始化參數。
例如:
<!-- 配置和映射 Servlet -->
<servlet>
<!-- Servlet 注冊的名字 -->
<servlet-name>helloServlet</servlet-name>
<!-- Servlet 的全類名 -->
<servlet-class>com.atguigu.javaweb.HelloServlet</servlet-class>
<!-- 配置 Serlvet 的初始化參數 -->
<init-param>
<!-- 參數名 -->
<param-name>user</param-name>
<!-- 參數值 -->
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>1230</param-value>
</init-param>
<!-- 可以指定 Servlet 被建立的時機 -->
<load-on-startup>-1</load-on-startup>
</servlet>
擷取初始化參數:
> getInitParameter(String name): 擷取指定參數名的初始化參數
> getInitParameterNames(): 擷取參數名組成的 Enumeration 對象.
String user = servletConfig.getInitParameter("user");
System.out.println("user: " + user);
Enumeration<String> names = servletConfig.getInitParameterNames();
while(names.hasMoreElements()){
String name = names.nextElement();
String value = servletConfig.getInitParameter(name);
System.out.println("^^" + name + ": " + value);
}
1.2、通過ServletConfig擷取Servlet的初始化參數
當servlet配置了初始化參數後,web容器在建立servlet執行個體對象時,會自動将這些初始化參數封裝到ServletConfig對象中,并在調用servlet的init方法時,将ServletConfig對象傳遞給servlet。進而,我們通過ServletConfig對象就可以得到目前servlet的初始化參數資訊
package com.atguigu.javaweb;
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* Servlet implementation class HelloServlet
*/
public class HelloServlet implements Servlet
@Override
public void destroy() {
System.out.println("destroy");
}
@Override
public ServletConfig getServletConfig() {
System.out.println("getServletConfig");
return null;
}
@Override
public String getServletInfo() {
System.out.println("getServletInfo");
return null;
}
@Override
public void init(ServletConfig servletConfig) throws ServletException {
String user = servletConfig.getInitParameter("user");
System.out.println("user: " + user);
Enumeration<String> names = servletConfig.getInitParameterNames();
while (names.hasMoreElements()) {
String name = names.nextElement();
String value = servletConfig.getInitParameter(name);
System.out.println("^^" + name + ": " + value);
}
System.out.println("init");
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
System.out.println("service");
}
public HelloServlet() {
System.out.println("HelloServlet's constructor");
}
}
2. ServletContext對象
目前 WEB 應用的一個大管家,從中擷取目前 WEB 應用的各方面資訊
Servlet 引擎 為 每個 Web 應用都建立了一個對應的 ServletContext對象,ServletContext 包含在 ServletConfig對象中
一個web 應用的 所有 Servlet 公用一個 ServletContext對象,是以ServletContext 被稱為 application 對象(Web 應用程式對象)
功能
- 擷取 web 應用程式的初始化參數
- 擷取日志
- application 域範圍的屬性
- 通路資源檔案
- 擷取虛拟路徑所映射的本地路徑
- WEB 應用之間的通路
2.1、多個Servlet通過ServletContext對象實作資料共享
public class ServletContextDemo1 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "xdp_gacl";
/**
* ServletConfig對象中維護了ServletContext對象的引用,開發人員在編寫servlet時,
* 可以通過ServletConfig.getServletContext方法獲得ServletContext對象。
*/
ServletContext context = this.getServletConfig().getServletContext();//獲得ServletContext對象
context.setAttribute("data", data); //将data存儲到ServletContext對象中
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws
public class ServletContextDemo2 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
String data = (String) context.getAttribute("data");//從ServletContext對象中取出資料
response.getWriter().print("data="+data);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws
先運作ServletContextDemo1,将資料data存儲到ServletContext對象中,然後運作ServletContextDemo2就可以從ServletContext對象中取出資料了,這樣就實作了資料共享。
2.2、擷取WEB應用的初始化參數
在web.xml檔案中使用
<context-param>
标簽配置WEB應用的初始化參數,如下所示:
<!-- 配置目前 WEB 應用的初始化參數 -->
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>jdbcUrl</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
擷取Web應用的初始化參數,代碼如下:
public class ServletContextDemo3 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletContext context = this.getServletContext();
//擷取整個web站點的初始化參數
String contextInitParam = context.getInitParameter("url");
response.getWriter().print(contextInitParam);
}
}
2.3、用servletContext實作請求轉發
public class ServletContextDemo4 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "<h1><font color='red'>abcdefghjkl</font></h1>";
response.getOutputStream().write(data.getBytes());
ServletContext context = this.getServletContext();//擷取ServletContext對象
RequestDispatcher rd = context.getRequestDispatcher("/servlet/ServletContextDemo5");//擷取請求轉發對象(RequestDispatcher)
rd.forward(request, response);//調用forward方法實作請求轉發
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws
public class ServletContextDemo5 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.getOutputStream().write("servletDemo5".getBytes());
}
.......
}
通路的是ServletContextDemo4,浏覽器顯示的卻是ServletContextDemo5的内容,這就是使用ServletContext實作了請求轉發
2.4、利用ServletContext對象讀取資源檔案
代碼範例:使用servletContext讀取資源檔案,讀取jdbc.properties
<!-- 配置目前 WEB 應用的初始化參數 -->
<!-- 配置目前 WEB 應用的初始化參數 -->
<context-param>
<param-name>driver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>jdbcUrl</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</context-param>
.getContextPath();
System.out.println(contextPath);
Properties pros = new Properties();
try {
ClassLoader classLoader = getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream("jdbc.properties");
System.out.println("1. " + is);
pros.load(is);
System.out.println(pros.getProperty("name"));
} catch (Exception e) {
e.printStackTrace();
}
pros = new Properties();
try {
InputStream is2 = servletContext.getResourceAsStream("/WEB-INF/classes/jdbc.properties");
System.out.println("2. " + is2);
pros.load(is2);
System.out.println(pros.getProperty("name"));
} catch (Exception e) {
e.printStackTrace();
}
String picPath = servletContext.getRealPath("/WEB-INF/lib");
System.out.println(picPath);
輸出結果:
3.四、在用戶端緩存Servlet的輸出
public class ServletDemo5 extends HttpServlet
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String data = "abcddfwerwesfasfsadf";
/**
* 設定資料合理的緩存時間值,以避免浏覽器頻繁向伺服器發送請求,提升伺服器的性能
* 這裡是将資料的緩存時間設定為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);
}
}