Please i am trying to store a player object in a HashTable which would then be stored in the ServletContext. When the class is called it is supposed to check if the player (object) is already in the playerList (HashTable) which is stored in the Servlet Context. But each time i call the class it shows that the player(object) isn't in the playerList (HashTable) so it creates a new Player object. I have tried including
this.getServletContext().setAttribute("playerList",playerList);
this.getServletConfig().getServletContext().setAttribute("playerList",playerList);
BUT it still is not working.
public class InitGameServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, JSONException {
response.setContentType("text/plain;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
ServletContext context = getServletContext();
Hashtable playerList = (Hashtable)context.getAttribute("playerList");
String playerid=request.getParameter("id");
HttpSession session=request.getSession(true);
Player player=null;
if(!playerList.contains(playerid)) {
player=new Player(playerid,50);
playerList.put(playerid, player);
System.out.println("This player wasnt there before so i have put it");
}
else {
player=(Player)playerList.get(playerid);
System.out.println("This player was there so i have retreived it");
}
}
}
}
@WebListener
public class InitializeGameContext implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext context = sce.getServletContext();
Hashtable<String, Game> gameList = new Hashtable();
context.setAttribute("gameList", gameList);
context.log("The game list has beeen loaded...............");
Hashtable<String, Player> playerList = new Hashtable();
context.setAttribute("playerList", playerList);
context.log("The playerList list has beeen loaded..................");
}
@Override
public void contextDestroyed(ServletContextEvent sce) {
}
}
In my web.xml i have
<listener>
<listener-class>web.InitializeGameContext</listener-class>
</listener>
EDIT: My complete web.xml
<servlet>
<servlet-name>InitGameServlet</servlet-name>
<servlet-class>com.whot.servlet.InitGameServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>InitGameServlet</servlet-name>
<url-pattern>/InitGameServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
3000
</session-timeout>
</session-config>
<listener>
<listener-class>web.InitializeGameContext</listener-class>
</listener>