The default-options "foo" and "bar" are only added for new requests
[demos/spring-boot] / src / main / java / de / juplo / demo / DemoController.java
1 package de.juplo.demo;
2
3
4 import java.util.LinkedHashMap;
5 import java.util.stream.Collectors;
6 import java.util.stream.Stream;
7 import lombok.extern.slf4j.Slf4j;
8 import org.springframework.stereotype.Controller;
9 import org.springframework.web.bind.annotation.ModelAttribute;
10 import org.springframework.web.bind.annotation.RequestMapping;
11 import org.springframework.web.bind.annotation.RequestParam;
12 import org.thymeleaf.util.StringUtils;
13
14
15 /**
16  * Controller to demonstrate the behavior of checkboxes
17  * @author Kai Moritz
18  */
19 @Controller
20 @Slf4j
21 public class DemoController
22 {
23   @ModelAttribute
24   public Form createForm(
25       @RequestParam(name = "name", required = false) String param)
26   {
27     Form form = new Form();
28     if (param == null)
29     {
30       form.map =
31         new LinkedHashMap<>(
32             Stream
33                 .of( "foo", "bar" )
34                 .collect(Collectors.toMap(a -> a, a -> false)));
35     }
36     return form;
37   }
38
39   @RequestMapping("/")
40   public String display(@ModelAttribute Form form)
41   {
42     log.info(
43         "option={}, inner={}{}",
44         form.option,
45         form.inner.option,
46         form.map
47             .entrySet()
48             .stream()
49             .map(entry -> entry.getKey() + "=" + entry.getValue())
50             .collect(Collectors.joining(", ", ", ", "")));
51     return "form";
52   }
53
54   @RequestMapping(path = "/", params = "add")
55   public String add(@ModelAttribute Form form, @RequestParam String name)
56   {
57     if (!StringUtils.isEmptyOrWhitespace(name))
58     {
59       form.map.put(name.trim(), Boolean.FALSE);
60       log.info("Added option \"{}\" to the map", name.trim());
61     }
62     else
63     {
64       log.info("Ignoring empty option-name");
65     }
66     return display(form);
67   }
68
69   @RequestMapping(path = "/", params = "remove")
70   public String remove(@ModelAttribute Form form, @RequestParam String remove)
71   {
72     Boolean value = form.map.remove(remove);
73     log.info("Removed option \"{}\" with value {} from the map", remove, value);
74     return display(form);
75   }
76 }