我有一個簡單的Person類:簡單的方法參數
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");
}
這當然可以通過反射API來完成,但問題在於它沒有比它的價值更麻煩,除非您經常遇到這種情況或者需要設置大量屬性。另外請記住,您可能想要進行一些驗證(「是給定的參數?」「是該字段有效的值?」) – johusman 2011-02-23 20:17:34
爲了您的理智,請將您的servlet重命名爲'PersonServlet'或其他東西。 – Jeremy 2011-02-23 20:17:44
謝謝johusman,我希望已經有東西了。驗證和其他邏輯稍後將在類的實例上完成。 – Simon 2011-02-23 20:18:28