在Java类中使用ServletContext [英] Using ServletContext in java class
本文介绍了在Java类中使用ServletContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我在 web.xml 中将数据保存为
I have the data in the web.xml as
<context-param>
<param-name>vDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
<!-- <description> ClassLoader of Driver </description>-->
</context-param>
<context-param>
<param-name>vConnection</param-name>
<param-value>jdbc:mysql://localhost:3306/cdr555</param-value>
<!-- <description> Connection to Database </description>-->
</context-param>
<context-param>
<param-name>vConnectionA</param-name>
<param-value>jdbc:mysql://localhost:3306/maindata</param-value>
<!-- <description> Connection to Database </description>-->
</context-param>
<context-param>
<param-name>vConnectionB</param-name>
<param-value>jdbc:mysql://localhost:3306/states_ap</param-value>
<!-- <description> Connection to Database </description>-->
</context-param>
<context-param>
<param-name>vConnectionP</param-name>
<param-value>jdbc:mysql://localhost:3306/personal</param-value>
<!-- <description> Connection to Database </description>-->
</context-param>
<context-param>
<param-name>vUsername</param-name>
<param-value>root</param-value>
<!-- <description> Username of Database </description>-->
</context-param>
<context-param>
<param-name>vPassword</param-name>
<param-value>sigma</param-value>
<!-- <description> Password of Database </description>-->
</context-param>
现在,我想使用以下代码在Java类文件中访问这些值:
Now, I want to access these values in the java class file by using the code:
ServletContext sc =getServletConfig().getServletContext();
String vDriver = sc.getInitParameter("vDriver");
String vConnection = sc.getInitParameter("vConnection");
String vConnectionA = sc.getInitParameter("vConnectionA");
String vConnectionB = sc.getInitParameter("vConnectionB");
String vConnectionP = sc.getInitParameter("vConnectionP");
String vUsername = sc.getInitParameter("vUsername");
String vPassword = sc.getInitParameter("vPassword");
使用上面的代码,我正在检索值.但是值并没有出现,而是给出了空值.
请给答复. 非常紧急
Using above code, I am retriving the values. But the values are not coming instead of that it is giving null values.
Please give the reply. its very urgent
推荐答案
您尝试读取的参数是上下文参数,但是您正在使用,而是将其存储为init参数:
The parameters you''re trying to read are context parameters, but you''re reading them usinggetInitParameter
, store them as init-parameters instead:
<init-param>
<param-name>local-server-port</param-name>
<param-value>4242</param-value>
</init-param
希望这会有所帮助,
弗雷德里克(Fredrik)
Hope this helps,
Fredrik
这篇关于在Java类中使用ServletContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文