如何快速拆分ServletRequest .getParameterMap()? [Spring MVC,ServletRequest]

时间:2015-04-16 15:52:36

标签: java spring list spring-mvc dictionary

我今天要向你提出的问题是这样的:

请求命中控制器(在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个不同的实体?

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

3 个答案:

答案 0 :(得分:3)

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

只需使用一个型号。在一个新对象中包裹Tom,Jerry和theRest:

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

public String processForm(@ModelAttribute Foo foo)

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

答案 1 :(得分:1)

这主要是对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)

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

答案 2 :(得分:0)

保留一个实用程序来检测密钥是指鼠标,猫还是其中没有一个。然后遍历整个键集并将它们放入相应的映射中。像这样的东西

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)但肯定是你能做的最好的事情。