Java library to map request parameters onto an object

Deadly 提交于 2019-12-24 00:14:20

问题


I have used stipes on a project in the past, and it has a great TypeConverter library that can take request parameters and route them into JavaBeans. It can even handle maps and arrays, such that:

class A {
 private int num;
 private Map<String, Integer> map;
 private List<String> list;
 ... setters and getters ...
}

<input type='text' name='num'/>
<input type='text' name='map["a"]'/>
<input type='text' name='map["b"]'/>
<input type='text' name='list[0]'/>
<input type='text' name='list[1]'/>

I have considered just pulling that bit of code out of stripes, but it seems like this library must exist, I just don't know what it is called.

Reference info: I have access to Java6 JDK, spring, and this happens to be for a Jersey web service MessageBodyReader implementation, basically I'd like to write a generic BeanHandlerMessageBodyReader


回答1:


Check the Apache Commons BeanUtils framework.

Here, a code snippet extracted from the User Guide

HttpServletRequest request = ...;
MyBean bean = ...;
HashMap map = new HashMap();
Enumeration names = request.getParameterNames();
while (names.hasMoreElements()) {
  String name = (String) names.nextElement();
  map.put(name, request.getParameterValues(name));
}
BeanUtils.populate(bean, map);

It can process indexed and mapped properties, and also lets you define your own converters.



来源:https://stackoverflow.com/questions/3959785/java-library-to-map-request-parameters-onto-an-object

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!