根据请求参数填充Javabeans的简便方法

时间:2011-02-23 20:08:19

标签: java forms servlets javabeans

我有一个简单的人类:

package simpleApp.entities;

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

    public void setSecondname(String cognome) {
        this.secondname = cognome;
    }
    public String getSecondname() {
        return secondname;
    }
    public void setName(String nome) {
        this.name = nome;
    }
    public String getName() {
        return name;
    }

}

和一个简单的html页面:

<html>
<body>

    <form action="/simpleApp/person/" method="POST">
        name: <input type="text" name="name"><br>
        second name: <input type="text" name="secondname"><br>
        <input type="submit">
    </form>

</body>
</html>

和一个简单的servlet:

public class Person extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public Person() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        //LOOK HERE:
        simpleApp.entities.Person p = new simpleApp.entities.Person();

        p.setName(request.getParameterValues("name")[0]);
        p.setSecondname(request.getParameterValues("secondname")[0]);

        response.sendRedirect("/simpleApp/index.html");
    }

}

有没有办法自动化参数设置?

这样的魔法
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        simpleApp.entities.Person p = new simpleApp.entities.Person();

        Magic.justSetEverything(p, request);

//      NOT NEEDED ANYMORE!!! MUAHAHAHA more time for coffee
//      p.setName(request.getParameterValues("name")[0]);
//      p.setSecondname(request.getParameterValues("secondname")[0]);

        response.sendRedirect("/simpleApp/index.html");
    }

2 个答案:

答案 0 :(得分:19)

因为经常使用Apache Commons BeanUtils

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

就是这样。

为了更进一步,您可以采用一个使用Javabeans作为模型的MVC框架,这样您根本不需要担心它们,例如JSFSpring MVC


与具体问题无关,在这个具体示例中使用getParameterValues()是笨拙的。只需使用getParameter()

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

答案 1 :(得分:0)

还有另一种方法。 SpringMvc可以为您自动绑定请求,但是您也可以手动执行。

final WebRequest servletWebRequest = new ServletWebRequest(request);
final WebRequestDataBinder binder = new WebRequestDataBinder(bean);
binder.bind(servletWebRequest);