使用 HashMap 作为 Form Backing Bean Spring MVC + ThymeLeaf [英] Use HashMap as Form Backing Bean Spring MVC + ThymeLeaf

查看:22
本文介绍了使用 HashMap 作为 Form Backing Bean Spring MVC + ThymeLeaf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am new to Spring MVC (coming from Grails). Is it possible to use a HashMap as a form backing bean?

在 Grails 中,可以从任何控制器操作访问名为 params 的对象.Params 只是一个映射,其中包含 POST 数据中包含的所有字段的值.根据我目前阅读的内容,我必须为我的所有表单创建一个表单支持 bean.

In Grails, one has access to an object called params from any controller action. Params is simply a map that contains the values of all the fields included in the POSTed data. From what I have read so far, I have to create a form backing bean for all of my forms.

可以使用 Maps 作为支持对象吗?

Is using Maps as the backing object possible?

推荐答案

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

You don't need to use form backing object for this. If you just want to access parameters that is passed in request (e.g. POST, GET ...) you need to get parameters map with HttpServletRequest#getParameterMap method. Look at example example that prints all parameters name and value to console.

另一方面.如果你想使用绑定,你可以将 Map 对象包装成表单支持 bean.

On the other hand. If you want to use binding you can wrap Map object into form backing bean.

控制器

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:/";
    }
}

ma​​in.html

<!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>

这篇关于使用 HashMap 作为 Form Backing Bean Spring MVC + ThymeLeaf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆