this is the first time I ask question here. I'm working on an rather small project that implement web chat using jsp and servlet. But I encounter a problem. I set an attribute in servletcontext using this
if(sc.getAttribute("queue")==null) //sc is servletcontext
{
sc.setAttribute("queue", new TreeMap<String,LinkedList<TreeMap<String,String>>>());
}
then I create a map in the attribute by this
if(sn.getAttribute(sn.getId())==null) //sn is a HttpSession object
{
//store nickname
sn.setAttribute(sn.getId(),request.getParameter("nickname"));
//store the new entry in Context
sc.setAttribute("queue",((TreeMap<String,LinkedList<TreeMap<String,String>>>)sc.getAttribute("queue")).put(sn.getId(),new LinkedList<TreeMap<String,String>>()));
}
I know the code isn't so elegant. It's my first time to really work on a project. The important thing now is that it can work.
All above is in my servlet file. Next I want to call a function which has the format as this “public static TreeMap>> messagePut(ServletContext sc)”
public static TreeMap>> messagePut(ServletContext sc)
Sorry there is some problem in the dispaly of the TreeMap, please see the concrete code above.
The discreet implementation is
public static TreeMap<String,LinkedList<TreeMap<String,String>>> messagePut(ServletContext sc)
{
//obtain message queue
TreeMap<String, LinkedList<TreeMap<String,String>>> temp=(TreeMap<String, LinkedList<TreeMap<String, String>>>)(sc.getAttribute("queue"));
//iterate
Set<String> keset=temp.keySet();
Iterator<String> it=keset.iterator();
TreeMap<String,LinkedList<TreeMap<String,String>>> mm=((TreeMap<String,LinkedList<TreeMap<String,String>>>)sc.getAttribute("queue"));
//object store stores a reproduce of the whole message queue
TreeMap<String,LinkedList<TreeMap<String,String>>> store=(TreeMap<String,LinkedList<TreeMap<String,String>>>)sc.getAttribute("queue");
while(it.hasNext())
{
//put the message into queue
//temp2 is user nickname
String temp2=(String)it.next();
if(temp2.equals(name))
continue;
else
{
TreeMap<String,String> c2=new TreeMap<String,String>();
c2.put(name,message);
LinkedList<TreeMap<String,String>> c3=store.get(temp2);
c3.add(c2);
store.put(temp2,c3);
}
}
return store;
}
I got a NullPointer exception in the above, this statement:
Set<String> keset=temp.keySet();
throw a nullpointer exception, I don't know why. But I have some doubt about this statement :
sc.setAttribute("queue",((TreeMap<String,LinkedList<TreeMap<String,String>>>)sc.getAttribute("queue")).put(sn.getId(),new LinkedList<TreeMap<String,String>>()));
TreeMap>>
is TreeMap<String,LinkedList<TreeMap<String,String>>>
.
I don't know whether this statement is correct.