+ -
当前位置:首页 → 问答吧 → WEB中一个关于静态方法和变量访问的问题

WEB中一个关于静态方法和变量访问的问题

时间:2011-12-05

来源:互联网

比如定义了一个类,一个静态变量,两个静态方法
public final class ConnectionPoolInit {
  private static String test = null;

  public static String getTest(){
  return test;
  }

  public static void setTest(String test){
  test = test;
  }
}

在一个servlet中赋值
public class TestServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request,response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  ConnectionPoolInit.setTest("abcd");
  }
}

在另一个servlet中取值
public class TestServlet extends HttpServlet {
  protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  doGet(request,response);
  }

  protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  String test = null;
  test = ConnectionPoolInit.getTest();
  System.out.println(test);
  }
}

为什么总是返回空呢

作者: sunny_1976   发布时间: 2011-12-05

又重新做了实验,没有错误
public static void setTest(String test){
  test = test;
  }
赋值有问题,这样变成自己给自己赋值了,参数名称改成test1就好了。

作者: sunny_1976   发布时间: 2011-12-05

test = test;
改成
 ConnectionPoolInit.test =test

作者: panmenghaha   发布时间: 2011-12-05

热门下载

更多