自認(rèn)為就是在web.xml中配置一些信息。然后在servlet當(dāng)中調(diào)用葛圃。
需要重學(xué)寫 下面的方法,來得到 ServletConfit對象
public void init(ServletConfig config) throws ServletException {}
上代碼
<servlet>
<description></description>
<display-name>ServketConfig</display-name>
<servlet-name>ServketConfig</servlet-name>
<servlet-class>jeno.servlet.ServketConfig</servlet-class>
<!-- 初始化參數(shù) config信息 -->
<init-param>
<param-name>xxx</param-name>
<param-value>yyy</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ServketConfig</servlet-name>
<url-pattern>/ServketConfig</url-pattern>
</servlet-mapping>
在servlet進(jìn)行如下調(diào)用
public class ServketConfig extends HttpServlet {
private ServletConfig config;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String value=config.getInitParameter("xxx");
response.getOutputStream().write(value.getBytes());
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
/**
* 初始化 Servlet的config 配置信息 config的信息 種子web.xml中進(jìn)行的
*/
@Override
public void init(ServletConfig config) throws ServletException {
String value= config.getInitParameter("xxx");
System.out.println(value);
//可以把 config 作為全局變量來使用
this.config=config;
//得到所有的 config 配置信息
//得到所有的配置 name屬性 根據(jù)name來的得到value
Enumeration en=config.getInitParameterNames();
while(en.hasMoreElements()){
String configName=(String)en.nextElement();
//得到 config value 之後就能進(jìn)行操作了了
String configValue=config.getInitParameter(configName);
}
}
}
接下里說 次config 配置用在什么地方
這個是解耦的,程序的靈活性得到提升蛛芥。
- 比如在xml中配置碼表
- 在xml中配置數(shù)據(jù)庫的連接信息
- 獲得配置文件燎含,查看struts案例的web.xml文件(后面會學(xué)到)
等等宾濒,這些信息一般不會寫死,都會靈活的進(jìn)行配置屏箍。所以放在 xml中進(jìn)行配置
String url="jdbc:mysql://localhost:3306/test";
String name="root";
String password="root";
//配置編碼信息
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/test</param-value>
</init-param>
<init-param>
<param-name>username</param-name>
<param-value>root</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>root</param-value>
</init-param>
尼瑪绘梦,在不用重寫 public void init(ServletConfig config) throws ServletException {}的情況下 直接調(diào)用 this.getServletConfig();即可得到想要的ServletConfig對象橘忱。因?yàn)楦割愔械?init()方法中已經(jīng)幫你實(shí)現(xiàn)。