Easy way of populating Javabeans based on request parameters

你说的曾经没有我的故事 提交于 2019-11-27 09:18:06
BalusC

For that Apache Commons BeanUtils is often used.

BeanUtils.populate(bean, request.getParameterMap());

That's it.

To get a step further, you can adopt a MVC framework which uses Javabeans as models so that you don't need to worry about them at all, such as JSF or Spring MVC.


Unrelated to the concrete question, using getParameterValues() is clumsy in this specific example. Just use getParameter().

p.setName(request.getParameter("name"));
p.setSecondname(request.getParameter("secondname"));

Yet another way to do it. SpringMvc can auto bind the request for you, but you can also do it mannually.

final WebRequest servletWebRequest = new ServletWebRequest(request);
final WebRequestDataBinder binder = new WebRequestDataBinder(bean);
binder.bind(servletWebRequest);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!