java - A more elegant way to handle different requests in the same servlet -
this question has answer here:
- design patterns web based applications 5 answers
this code of servlet:
protected void processrequest(httpservletrequest request, httpservletresponse response) throws servletexception, ioexception { string result = (string)request.getparameter("action"); switch (result) { case "init": request.setattribute("countrieslist", signupbean.getcontrieslist()); string arg = "/signup.jsp"; requestdispatcher dispatcher = this.getservletcontext().getrequestdispatcher(arg); dispatcher.forward(request, response); break; case "submit": //code handle request break; } }
when click on link signup?action=init
servlet initialized receiving countries list , passing signup.jsp
page in order show list on select form element. when compile signup form, push submit button has action="signup?action=submit" in way servlet can handle request. know more elegant way or correct way mean?
create interface action
, several implementations. in case init
, submit
. register these actions in init method of servlet, stored in map<string, action> actions
.
now processrequest()
like:
string actionname = (string)request.getparameter("action"); action action = actions.get(actionname); action.perform();
however seems try re-invent wheel. use 1 of available frameworks. example struts approximately explained here. spring stronger , has same concept.
Comments
Post a Comment