The default-options "foo" and "bar" are only added for new requests
[demos/spring-boot] / src / main / java / de / juplo / demo / DemoController.java
index b841780..52fc4fe 100644 (file)
@@ -1,11 +1,15 @@
 package de.juplo.demo;
 
 
+import java.util.LinkedHashMap;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.stereotype.Controller;
 import org.springframework.web.bind.annotation.ModelAttribute;
 import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RequestParam;
+import org.thymeleaf.util.StringUtils;
 
 
 /**
@@ -16,6 +20,22 @@ import org.springframework.web.bind.annotation.RequestMapping;
 @Slf4j
 public class DemoController
 {
+  @ModelAttribute
+  public Form createForm(
+      @RequestParam(name = "name", required = false) String param)
+  {
+    Form form = new Form();
+    if (param == null)
+    {
+      form.map =
+        new LinkedHashMap<>(
+            Stream
+                .of( "foo", "bar" )
+                .collect(Collectors.toMap(a -> a, a -> false)));
+    }
+    return form;
+  }
+
   @RequestMapping("/")
   public String display(@ModelAttribute Form form)
   {
@@ -30,4 +50,27 @@ public class DemoController
             .collect(Collectors.joining(", ", ", ", "")));
     return "form";
   }
+
+  @RequestMapping(path = "/", params = "add")
+  public String add(@ModelAttribute Form form, @RequestParam String name)
+  {
+    if (!StringUtils.isEmptyOrWhitespace(name))
+    {
+      form.map.put(name.trim(), Boolean.FALSE);
+      log.info("Added option \"{}\" to the map", name.trim());
+    }
+    else
+    {
+      log.info("Ignoring empty option-name");
+    }
+    return display(form);
+  }
+
+  @RequestMapping(path = "/", params = "remove")
+  public String remove(@ModelAttribute Form form, @RequestParam String remove)
+  {
+    Boolean value = form.map.remove(remove);
+    log.info("Removed option \"{}\" with value {} from the map", remove, value);
+    return display(form);
+  }
 }