【问题标题】:Use HashMap as Form Backing Bean Spring MVC + ThymeLeaf使用 HashMap 作为表单支持 Bean Spring MVC + ThymeLeaf
【发布时间】:2014-10-09 17:37:54
【问题描述】:

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

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

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

【问题讨论】:

    标签: spring-mvc thymeleaf


    【解决方案1】:

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

    另一方面。如果要使用绑定,可以将 Map 对象包装到表单支持 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>
    

    【讨论】:

    • 谢谢!这正是我所需要的。
    • @michal.kreuzman 你能帮我解决我的问题吗?我无法在 jsp
    猜你喜欢
    • 2015-09-25
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    相关资源
    最近更新 更多