使用HashMap作为Form Backing Bean Spring MVC + ThymeLeaf

Use HashMap as Form Backing Bean Spring MVC + ThymeLeaf

我是Spring MVC的新手(来自Grails)。 是否可以将HashMap用作表单支持bean?

在Grails中,可以从任何控制器操作访问称为params的对象。 参数只是一个映射,其中包含POSTed数据中包含的所有字段的值。 到目前为止,我必须为我的所有表单创建一个表单支持bean。

是否可以将地图用作支持对象?


您不需要为此使用表单支持对象。 如果只想访问请求中传递的参数(例如POST,GET ...),则需要使用HttpServletRequest#getParameterMap方法获取参数映射。 查看将所有参数名称和值打印到控制台的示例示例。

另一方面。 如果要使用绑定,可以将Map对象包装到表单支持bean中。

控制者

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import java.util.Arrays;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
public class ParameterMapController {

    @RequestMapping(value ="/", method = RequestMethod.GET)
    public String render() {
        return"main.html";
    }

    @RequestMapping(value ="/", method = RequestMethod.POST)
    public String submit(HttpServletRequest req) {
        Map<String, String[]> parameterMap = req.getParameterMap();
        for (Entry<String, String[]> entry : parameterMap.entrySet()) {
            System.out.println(entry.getKey() +" =" + Arrays.toString(entry.getValue()));
        }

        return"redirect:/";
    }
}

main.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8" />
</head>
<body>

<form th:action="@{/}" method="post">
    <label for="value1">Value 1</label>
    <input type="text" name="value1" />

    <label for="value2">Value 2</label>
    <input type="text" name="value2" />

    <label for="value3">Value 3</label>
    <input type="text" name="value3" />

    <input type="submit" value="submit" />
</form>

</body>
</html>