Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Servlets: How to share common behaviour among multiple servlets?

Tags:

java

servlets

Let's say I have multiple servlets with minor differences in doPost() implementation. Example code here. I want to be able to define function just once and avoid duplication of code among different servlets.

One way is to put common behaviour in a different class altogether and have object of that class in every Servlet to use common behaviour but would that be a good idea?

What are some other alternatives to tackle this issue?

like image 964
aamir Avatar asked Jun 06 '26 02:06

aamir


2 Answers

You might create an abstract class that implements Httpservlet and defines all the common methods, but leaves your modifiable (doGet) method abstract.

like image 103
Anarki Avatar answered Jun 07 '26 15:06

Anarki


I think this:

One way is to put common behaviour in an altogether different class and have object of that class in every Servlet to use common functionality but that is not very elegant

is actually quite elegant. It sound like you're describing composition. It reduces code duplication, extracts common functionality into a single component and mitigates the issues you'd get through implementation inheritance.

like image 38
Brian Agnew Avatar answered Jun 07 '26 15:06

Brian Agnew