请我尝试将播放器对象存储在 HashTable 中,然后将其存储在 ServletContext 中。当类被调用时,它应该检查播放器(对象)是否已经在存储在 Servlet 上下文中的 playerList(HashTable)中。但是每次我调用该类时,它都会显示 player(object) 不在 playerList (HashTable) 中,因此它会创建一个新的 Player 对象。我试过包括
this.getServletContext().setAttribute("playerList",playerList);
this.getServletConfig().getServletContext().setAttribute("playerList",playerList);
但它仍然无法正常工作。
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) {
}
}
在我的 web.xml 我有
<listener>
<listener-class>web.InitializeGameContext</listener-class>
</listener>
编辑:我完整的 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>