gpt4 book ai didi

java - 基于请求参数填充 Javabeans 的简单方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:03:28 24 4
gpt4 key购买 nike

我有一个简单的人类:

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");
}

最佳答案

为此Apache Commons BeanUtils经常使用。

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

就是这样。

更进一步,您可以采用以 Javabeans 作为模型的 MVC 框架,这样您就完全不需要担心它们,例如 JSFSpring MVC .


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

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

关于java - 基于请求参数填充 Javabeans 的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5096454/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com