我的工程在web-inf下建立了一个xml文件
在后面的程序中要用到这个文件,我的获取文件位置是这么弄的,
先定义一个类产生全局变量public class ConstantsUtil {
public static String realPath;
}在定一个servletpublic class StartUpServlet extends HttpServlet {
public void init() throws ServletException{
System.out.println("正在加载StartUpServlet....");
ConstantsUtil.realPath=getServletContext().getRealPath("/WEB-INF/");
System.out.println("------------"+ConstantsUtil.realPath);
}
}并在web.xml中配置servlet
在每次启动服务器的时候StartUpServlet都能正常加载且正确打印出WEB-INF的绝对地址
但是当我在程序中用
new File(ConstantsUtil.realPath+"\\daoContext.xml")
或者直接输出
System.out.println(ConstantsUtil.realPath+"\\daoContext.xml");得到的ConstantsUtil.realPath是为null
难道这个全局变量设定有错?谢谢大家
在后面的程序中要用到这个文件,我的获取文件位置是这么弄的,
先定义一个类产生全局变量public class ConstantsUtil {
public static String realPath;
}在定一个servletpublic class StartUpServlet extends HttpServlet {
public void init() throws ServletException{
System.out.println("正在加载StartUpServlet....");
ConstantsUtil.realPath=getServletContext().getRealPath("/WEB-INF/");
System.out.println("------------"+ConstantsUtil.realPath);
}
}并在web.xml中配置servlet
在每次启动服务器的时候StartUpServlet都能正常加载且正确打印出WEB-INF的绝对地址
但是当我在程序中用
new File(ConstantsUtil.realPath+"\\daoContext.xml")
或者直接输出
System.out.println(ConstantsUtil.realPath+"\\daoContext.xml");得到的ConstantsUtil.realPath是为null
难道这个全局变量设定有错?谢谢大家
才对,,主要是getServletContext().getRealPath("/WEB-INF/");没取得值吧
public void init() throws ServletException{
System.out.println("正在加载StartUpServlet....");
ConstantsUtil.realPath=getServletContext().getRealPath("/WEB-INF/");
System.out.println("$$$$$$$$$$$$$$$$$$$"+getServletContext());
System.out.println("------------"+ConstantsUtil.realPath);
}
}启动服务器的时候打印有这个
信息: SessionListener: contextInitialized()
正在加载StartUpServlet....
$$$$$$$$$$$$$$$$$$$org.apache.catalina.core.ApplicationContextFacade@dc4c81
------------D:\Tomcat6\webapps\helphandcrm\WEB-INF
System.out.println("正在加载StartUpServlet....");
ConstantsUtil.realPath=getServletContext().getRealPath("/WEB-INF/");
System.out.println("------------"+ConstantsUtil.realPath);
}
虽然我不知道你的全局变量到底是怎么全局的。
但我觉得你的 问题肯定出在ConstantsUtil.realPath 这个地方。
你在别的地方 调用 ConstantsUtil.realPath 除非你的 ConstantsUtil
是单例的,否则的话就不会是同一个对象。那么你访问的 ConstantsUtil.realPath
就自然回为空。
第二:你的那个static 变量在另外的一个文件中,只会以空来出现。虽然你在init()中定义了。
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>servlet.Servlet1</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>servlet:............
public void init() throws ServletException {
a.value = this.getServletContext().getRealPath("/WEB-INF/");
System.out.println(a.value);
}
jsp:
<%
out.println(listener.a.value);
%>输出结果:
E:\Java\StrutsTest\WebModule2\WEB-INF