Reputation: 1246
I'm writing a blog on Java, now I have have 2 servlets models, in first I write functions to manipulate with articles, and in second to manipulate with categories. When I add new article, I should have all categories in dropdown list on my form. How can I call from my servlet ArticleMod, function getCategoryList() which already placed in CategoryMod servlet;
Here's code of function:
public Category[] getCategoryList() throws Exception {
db data = new db();
Connection con = data.OpenConnection();
PreparedStatement statement = con.prepareStatement("SELECT * FROM `category`");
ResultSet result = statement.executeQuery();
int size = 0;
if (result != null)
{
if (result.last()) {
size = result.getRow();
result.beforeFirst();
}
}
Category[] categories = new Category[size];
int i = 0;
while(result.next()){
categories[i] = new Category (
result.getInt(1),
result.getString(2),
result.getString(3));
i++;
}
return categories;
}
on this servlet im use it like that
if (request.getParameter("todo").equals("show_category_list")) {
try {
Category[] categories = this.getCategoryList();
request.setAttribute("categories", categories);
RequestDispatcher dispatcher = request.getRequestDispatcher("category/category_list.jsp");
dispatcher.forward(request, response);
} catch (Exception e) {
}
}
How can I call that function from other servlet?
Upvotes: 1
Views: 2843
Reputation: 6890
You can use a Parent Abstract class for two servlet and putting shared behavior there. for sample see following code:
public abstract class ParentServlet extends HttpServlet
{
public Category[] getCategoryList() throws Exception
{
/**
* Your getCategoryList codes
*/
}
}
class ChildServelt_1 extends ParentServlet
{
@Override
public void service(ServletRequest arg0,
ServletResponse arg1) throws ServletException, IOException
{
/*
* Do write your business
*/
super.getCategoryList();
}
}
class ChildServelt_2 extends ParentServlet
{
@Override
public void service(ServletRequest arg0,
ServletResponse arg1) throws ServletException, IOException
{
/*
* Do write your business
*/
super.getCategoryList();
}
}
when two method have shared behavior they are may have a Parent
, it is a rule of OOP.
Upvotes: 1
Reputation: 81684
Move the method either to a common base class for the two servlets, or to a utility class that both servlets can share. Writing the two servlets to depend arbitrarily on one another this way would be a bad design.
Upvotes: 3