相对路径:sun servlet规范推荐放在WEB-INF目录里

解决方案 »

  1.   

    那么程序中的路径该怎么写呢?
    我是第一次写servlet程序,很多地方缺乏经验,请各位指导。
      

  2.   

    1:阅读关于TOMCAT的配置文件web.xml。
    2:用相对路径的话,配置可以和类文件放到一起,String classPath = YourClass.class.getResource("").getFile();就可以得到你的类的路径。
    3:可以通过System.getProperty(key)方法,但运行程序时应加上-D参数,参考java命令的参数。写Servlet最好就是学会用/WEB-INF/web.xml
      

  3.   

    多谢,能不能再给个提醒,看web.xml的哪一块比较合适。
      

  4.   

    有几种方法, 其实不需要写配置文件什么的, 直接写在 web.xml 中就好了;
    下面是一些例子, 供你参考:
    1)作为 Servlet 的初始化参数 :
    <web-app>
    ......
      <servlet>
        <servlet-name>TestServlet</servlet-name>
        <servlet-class>TestServlet</servlet-class>
        <init-param>
            <param-name>userName</param-name>
            <param-value>Peter Zhou</param-value>
        </init-param>
      </servlet>
    ......
    </web-app>
    在 TestServlet 中就可以使用下面的代码获得 userName 了:
    ......
    public class TestServlet extends HttpServlet {
        private String sInput = "unknown" ;
        private String sInit = "" ;
        /** Initializes the servlet.
         */
        public void init(ServletConfig config) throws ServletException {
            super.init(config);
            sInit = config.getInitParameter("userName");
        }
    ......2)作为 Web Application 的初始化参数
    <web-app>
      <!-- 数据源的 JNDI 名称 -->
      <context-param>
        <param-name>dataSource</param-name>
        <param-value>jdbc/myDB</param-value>
      </context-param>
    ......
    </web-app>
    在 Servlet 或者 JSP 中可以使用如下的代码访问
        public void init(ServletConfig config) throws ServletException {
            ServletContext app ;
            app = config.getServletContext();
            String sDataSource = app.getInitParameter("dataSource");
            ......
    如果使用 jsp, 可以直接用 application.getInitParameter("dataSource"):)