一、ServletConfig概述
ServletConfig 代表當前Servlet在web.xml中的配置信息。
在Servlet的配置文件中,可以使用一個或多個標簽為servlet配置一些初始化參數(shù)。當servlet配置了初始化參數(shù)后,web容器在創(chuàng)建servlet實例對象時,會自動將這些初始化參數(shù)封裝到ServletConfig對象中,并在調(diào)用servlet的init()方法時,將ServletConfig對象傳遞給servlet。進而,程序員通過ServletConfig對象就可以得到當前servlet的初始化參數(shù)信息。
二、ServletConfig類的方法
①String getServletName()
獲取當前Servlet在web.xml中配置的名字
②String getInitParameter(String name)
獲取當前Servlet指定名稱的初始化參數(shù)的值
③Enumeration getInitParameterNames()
獲取當前Servlet所有初始化參數(shù)的名字組成的枚舉
④ServletContext getServletContext()
獲取代表當前web應(yīng)用的ServletContext對象
三、ServletConfig使用實例
import java.io.IOException;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SConfigServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
ServletConfig config = this.getServletConfig();
//--獲取當前Servlet 在web.xml中配置的名稱
String sName = config.getServletName();
System.out.println(sName);
//--獲取當前Servlet中配置的初始化參數(shù)
String value = config.getInitParameter("name1");
System.out.println(value);
Enumeration enumeration = config.getInitParameterNames();
while(enumeration.hasMoreElements())
{
String name = (String) enumeration.nextElement();
String value = config.getInitParameter(name);
System.out.println(name+":"+value);
}
//-------------------獲取ServletContext對象-------------------
//方式一
ServletContext context = config.getServletContext();
//方式二
this.getServletContext();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
doGet(request, response);
}
}
對應(yīng)的web.xml配置文件:
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> SConfigServlet index.jsp 原文鏈接:https://blog.csdn.net/m0_49828549/article/details/114236530<servlet-class>SConfigServletservlet-class>
<init-param>
<param-name>name1param-name>
<param-value>value1param-value>
init-param>
<init-param>
<param-name>encodeparam-name>
<param-value>utf-8param-value>
init-param>
<servlet-name>SConfigServletservlet-name>
<url-pattern>/servlet/SConfigServleturl-pattern>
-
封裝
+關(guān)注
關(guān)注
128文章
8684瀏覽量
145486 -
前端
+關(guān)注
關(guān)注
1文章
214瀏覽量
18282 -
代碼
+關(guān)注
關(guān)注
30文章
4900瀏覽量
70738
發(fā)布評論請先 登錄



Servlet入門----創(chuàng)建第一個自己的Servlet小程序
如何使用Python的類? 優(yōu)勢有哪些?
基于數(shù)據(jù)連續(xù)性的聚類方法

Java數(shù)組的常用方法_Java:數(shù)組工具類Arrays類的常用方法的用法及代碼
super調(diào)用父類的構(gòu)造方法

評論