我想保留一个静态字符串数组来保存客户端调用服务器时传递的变量,然后能够使用 getter 从客户端访问它们。
出于某种原因,我只能使用非常基本的类型(例如 int 而不是 Integer)来工作,其他所有类型都会引发空指针异常。
这是一个代码片段。 (使用 GWT)
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements AddElection
{
//this seems to be throwing a NullPointerException:
static String[] currentElections;
static int index;
public String electionServer(String input) {
// save currently running elections
currentElections[index] = input;
index = index + 1;
// TODO: getcurrentElections
所以。我的问题是,如果我想在服务器端临时存储一个字符串数组并能够访问它,我该如何在 google web toolkit 中执行此操作? 谢谢!
最佳答案
您尚未初始化静态数组。
至少你必须做这样的事情:
static String[] currentElections = new String[ 100 ];
但是你的数组似乎会随着时间的推移而增长,所以最好使用集合类:
static List<String > currentElections = new ArrayList<String >();
public String electionServer(String input) {
// save currently running elections
currentElections.add( input );
}
但是如果可以从多个客户端同时调用此方法,请小心。然后你必须像这样同步访问:
static List<String > currentElections =
Collections.synchronizedList( new ArrayList<String >() );
关于Java:服务器端类上的静态字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2257787/