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