* or to handle exceptions.
*/
void handleRequest(HttpServletRequest req) {
// Get elements from the session
HttpSession session = req.getSession();
Game game = (Game) session.getAttribute(SESSION_GAME_KEY);
// Create game or reset it if necessary
String resetStr = req.getParameter(PARAM_RESET_KEY);
if ((game == null) || (resetStr != null)) {
// TODO use dependency injection to avoid dependency on implementation
game = GAME_FACTORY.createGame();
game.begin();
}
// Handle play parameter
String subMessage = "";
String colStr = req.getParameter(PARAM_PLAY_KEY);
if (colStr != null) {
try {
int colIdx = Integer.parseInt(colStr);
game.dropDisc(colIdx - 1);
} catch (NumberFormatException e) {
subMessage = "Invalid parameter col: " + colStr;
log.error("Invalid column", e);
} catch (ConnectFourException e) {
subMessage = e.getMessage();
log.error("Unable to play", e);
}
}
// Build main message
String mainMessage = "";
if (game.getStatus() == GameStatus.ONGOING) {
Player player = game.getCurrentPlayer();
mainMessage = "Now playing: " + player.getName();
} else if (game.getStatus() == GameStatus.FINISHED) {
Player winner = game.getWinner();
if (winner != null) {
mainMessage = winner.getName() + " won the game.";
} else {
mainMessage = "It's a draw game.";
}
}
// Save request attributes for the view
req.setAttribute(ATTR_MAIN_MESSAGE_KEY, mainMessage);
req.setAttribute(ATTR_SUB_MESSAGE_KEY, subMessage);
req.setAttribute(ATTR_GAME_ID_KEY, game.getId());
// Save elements in the session
session.setAttribute(SESSION_GAME_KEY, game);
}