Easy way of populating Javabeans based on request parameters

后端 未结 2 1312
轻奢々
轻奢々 2020-12-01 22:19

I have a simple person class:

package simpleApp.entities;

public class Person {
    private String name;
    private String secondname;

    public void set         


        
相关标签:
2条回答
  • 2020-12-01 22:49

    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);
    
    0 讨论(0)
  • 2020-12-01 22:58

    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"));
    
    0 讨论(0)
提交回复
热议问题