有关ServletConfig与ServletContext的访问

网友投稿 209 2023-06-18


有关ServletConfig与ServletContext的访问

一般来说,对于整个应用的配置,为了不使用"硬编码",应该使用ServletContext对象。

而如果只有一个特定的Servlet需要设定的参数,其他Servlet不能访问,那么一般要使用ServletConfig();

PS: 在使用ServletConfig对象的时候,在init()方法中,一定要用super类初始化ServletConfig对象。

public void init(ServletConfig http://config) throws ServletException

{

super.init(config);

//TODO

}

下面来逐个讨论:

一、ServletContext对象

元素:设定Context起始参数

在web.xml中,您可以利用元素来定义Context起始参数,它包含两个子元素:

n :定义Context起始参数名称

n :定义Context起始参数值

以下是元素的使用范例,在本例中笔者定义了两个Context起始参数:

n driver_type:Web应用程序欲使用的JDBC驱动程序名称

n url:目标数据库位置

driver_type

oracle.jdbc.driver.OracleDriver

url

jdbc:oracle:thin:@IP:1521:SID

有两种方式存取Context起始参数的方式:

表1 在ServletContext接口中用来存取Context起始参数的方法

方法名称

回传类型

用 途

getInitParameter()

String

取得某个Context起始参数值

getInitParameterNames()

java.util.Enumeration

取得所有ContexyWMwjjlgMWt起始参数

1. 先调用getServletConfig()方法取得ServletConfig对象,再利用ServletConfig接口定义的getServletContext()方法取得ServletContext对象。

ServletConfig config = getServletConfig();

ServletContext context = config.getServletContext();

String driver_type = context.getInitParameter("drvier_type");

String url=context.getInitParameter("url");

2. 直接调用getServletContext()方法取得ServletContext对象。

ServletContext context = getServletContext();

//获得配置的参数

String driver_type = context.getInitParameter("drvier_type");

String url=context.getInitParameter("url");

//获得当前WebApp的路径

String path=context.getRealPath("/");

二, ServletConfig对象

元素:设定init起始参数

在web.xml中,您可以利用元素来定义Config起始参数,它包含两个子元素:

n :定义Config起始参数名称

n :定义Config起始参数值

以下是元素的使用范例,在本例中笔者定义了两个Config起始参数:

n driver_type:Web应用程序欲使用的JDBC驱动程序名称

n url:目标数据库位置

testServlet

com.simon.test.servlet.initparam.testServlet

driver_type

oracle.jdbc.driver.OracleDriver

url

jdbc:oracle:thin:@IP:1521:SID

testServlet

/testServlet

在init()方法中,应该:

public void init(ServletConfig config) throws ServletException

{

//必须要继承super类的init()方法

super.init(config);

String filename=getServletConfig().getInitParameter("config-file");

//TODO

}


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:java struts2框架简介
下一篇:微信小程序 图片边框解决方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~