java - Easy way of populating Javabeans based on request parameters -
i have simple person class:
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; } }
and simple html page:
<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>
and simple 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"); } }
is there way automate parameter setting?
something magic like
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 coffee // p.setname(request.getparametervalues("name")[0]); // p.setsecondname(request.getparametervalues("secondname")[0]); response.sendredirect("/simpleapp/index.html"); }
for apache commons beanutils used.
beanutils.populate(bean, request.getparametermap());
that's it.
to step further, can adopt mvc framework uses javabeans models don't need worry them @ all, such jsf or spring mvc.
unrelated concrete question, using getparametervalues()
clumsy in specific example. use getparameter()
.
p.setname(request.getparameter("name")); p.setsecondname(request.getparameter("secondname"));
Comments
Post a Comment