【问题标题】:How to split a ServletRequest .getParameterMap() effincietly? [Spring MVC,ServletRequest]如何有效地拆分 ServletRequest .getParameterMap()? [Spring MVC,ServletRequest]
【发布时间】:2015-04-16 15:52:35
【问题描述】:

我今天想给你提出的问题是这样的:

一个请求到达一个控制器(在 Spring MVC 环境中),在那个控制器中,我想以某种方式拆分请求参数。我最初的方法是使用 @ModelAttribute 注释

public String processForm(@ModelAttribute Mouse tom, @ModelAttribute Mouse jerry)

但是通过这种方法,我将如何获得其他参数?这是有效的吗?

所以我想做这样的事情:

Mouse jerry = new Mouse();
BeanUtils.populate(jerry, request.getParameterMap());
//do something to remove the mice :) how?
Cat tom = new Cat();
BeanUtils.populate(cat, request.getParameterMap());
//do something to remove the cats how?
BeanUtils.populate(theRest, request.getParameterMap());

最后的问题是:如何通过尽可能少地遍历列表来有效地将请求拆分为 3 个不同的实体?

感谢您阅读本文,并希望得到答复。

【问题讨论】:

    标签: java spring list spring-mvc dictionary


    【解决方案1】:

    我认为您是在问如何在处理程序方法中处理多个对象,而不是实际拆分表单/查询参数,是吗?

    只使用一种模型。将 Tom、Jerry 和 theRest 包裹在一个新对象中:

    class Foo {
      Cat tom;
      Mouse jerry;
      Bar theRest;    
      ...
    }
    

    public String processForm(@ModelAttribute Foo foo)
    

    Spring MVC 可以为你data bind。你不需要 BeanUtils。

    【讨论】:

    • 如果我不知道 Bar 对象将包含什么?例如,请求将如下所示:&cat.name=Tom&mouse.name=Jerry&unknownAttribute=abc&unknownAttribute2=dcf。如何创建 Foo 类以使其仅包含 unknown* 属性?
    【解决方案2】:

    这主要是对Neil McGuiguan的回答的补充。

    你必须知道 Spring MVC 在模型属性中存储请求参数的方式忽略了模型属性的名称,但尊重下面命名的层次结构。

    所以你可以:

    class Mouse {
        String name;
        ...
        // getters and setters omitted
    }
    
    class Cat {
        String name;
        ...
    }
    
    class Foo foo {
        Mouse jerry;
        Cat tom;
        ...
    }
    

    在你的 HTML 中(可以通过 Spring MVC 标签生成...)

    <form ...>
        <input type="text" name="jerry.name"/>
        <!-- other fields for jerry -->
        <input type="text" name="tom.name"/>
        <!-- ...-->
    </form>
    

    这样:

    public String processForm(@ModelAttribute Foo foo, BindingResult result)
    

    将使用适当的请求参数自动填充您的所有字段。

    【讨论】:

      【解决方案3】:

      保留一个实用程序来检测键是指鼠标、猫还是两者都不是。然后遍历整个键集并将它们放入相应的映射中。像这样的

      for (Map.Entry<String, String> entry : requestParamMap.entrySet()) {
          if (isMouse(entry.getKey())) {
            jerry.put(entry.getKey(), entry.getValue);
          } else if (isCat(entry.getKey())) {
            cat.put(entry.getKey(), entry.getValue);
          } else {
            theRest.put(entry.getKey(), entry.getValue);
          }
      }
      

      不是O(n),但肯定是你能做的最好的事情,让事情变得简单。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-07-23
        • 1970-01-01
        • 2018-11-15
        • 1970-01-01
        • 2014-04-25
        • 2016-07-26
        • 2013-02-07
        • 1970-01-01
        相关资源
        最近更新 更多