Instead of writing too many sql statements in each servlet I just want to write one sql statement in a java class and want to call that class from each servlet but I have not found the correct way to do so.
The sql statement is: select distinct username from table where userid=?
while (rs.next){
username=rs.getString(1);
}
I want to return username to each servlet
so I created a java class in netbeans:
public class Username {
//How should I proceed here?
}
Don’t embed that code in a servlet.
Create a separate POJO that does the work for you. Write it, test it, and give a reference to any servlet that needs its services. Let the servlet call the one method that executes that logic.
Start with an interface:
Then give it an implementation:
Your servlet will have a reference to it:
The servlet should acquire the Connection from a pool and give it to the DAO.
If you have write operations, I’d recommend that you create a separate service layer. Services know about units of work. They’ll outlive your web UI and those servlets.