0

I have a web page where users can fill in and submit forms:

 <form id=email...
 send email ....
 <input type="hidden"id="method" value="sendemail"...
 />
  .............

 <form id=writeindatabase
 some data
      ............
 <input type="hidden"id="method"  value="writeindatabase"...

On the server side:

if (method.compareTo("sendemail")==0) {
 doSendEmail(....
}
else if (method.compareTo("writeindatabase")==0) {
  doWriteInDatabase(....

 ..............................

I don't like this architecture because it violates the open close principle. Is it possible to refactor this to fix that? Thanks.

Andrew Barber
  • 39,603
  • 20
  • 94
  • 123
user710818
  • 23,228
  • 58
  • 149
  • 207
  • why don't you just have both forms redirect to different URLs? – kutschkem Feb 21 '13 at 14:25
  • What you could do is change the `action` attribute in your form and let the Container dispatch to the correct Servlet or Controller (eg. if you're using Spring). – Sotirios Delimanolis Feb 21 '13 at 14:26
  • I use MVC. It is only 1 web page. For 1 web page create many servlets and controllers - will be more repeatable code. Answer should be the same page with added result of operation. Now I have 1 web page, 1 controller 1 view model. If I will create many servlets and controllers for 1 web page it will be difficult to make it work toghether. – user710818 Feb 21 '13 at 14:33
  • I think about reflection. But not sure. – user710818 Feb 21 '13 at 14:34

1 Answers1

2

You can use reflection in a structured, secure manner, or, similarly the Command Pattern.

  • Reflection: make a Map<String, Method> that maps each acceptable method name to a Reflection Method object which you can invoke after looking it up.

  • Command Pattern: use a Map<String, Callable<?>> in a manner similar to above. Instantiate the Callables as anonymous inner classes that implement call by invoking the appropriate service method.

Marko Topolnik
  • 195,646
  • 29
  • 319
  • 436