package org.geekhub.dt;
import org.geekhub.dt.objects.Animal;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.*;
@WebServlet(urlPatterns = "/submit")
public class AddItemServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name = request.getParameter("name").trim();
String value = request.getParameter("value").trim();
HttpSession session = request.getSession();
TreeMap<String, List<Animal>> map = (TreeMap<String, List<Animal>>) session.getAttribute("map");
if (map == null) {
map = new TreeMap<>();
}
Integer id = (Integer) session.getAttribute("id");
if (id == null) {
id = 1;
}
if (!name.equals("") && !value.equals("")) {
addItemToMap(map, id, name, value);
}
session.setAttribute("id", ++id);
session.setAttribute("map", map);
request.getRequestDispatcher("/index.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
private void addItemToMap(TreeMap<String, List<Animal>> map, int id, String name, String value) {
List<Animal> animals;
if (map.containsKey(name)) {
animals = map.get(name);
} else {
animals = new ArrayList<>();
}
animals.add(new Animal(id, name, value));
map.put(name, animals);
}
}