我正在写一篇关于Java的博客,现在我有2个servlet模型,首先我编写了用文章操作的函数,然后用类别操作。当我添加新文章时,我应该在表单上的下拉列表中包含所有类别。如何从我的servlet调用ArticleMod,函数getCategoryList()已经放在CategoryMod servlet中;
这是功能代码:
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;
}
在这个servlet上使用它就像那样
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) {
}
}
如何从其他servlet调用该函数?
答案 0 :(得分:3)
将方法移动到两个servlet的公共基类,或移动到两个servlet可以共享的实用程序类。写这两个servlet以这种方式任意相互依赖将是一个糟糕的设计。
答案 1 :(得分:1)
您可以将Parent Abstract类用于两个servlet并在其中放置共享行为。有关示例,请参阅以下代码:
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();
}
}
当两个方法共享行为时,它们可能有一个Parent
,这是一个OOP规则。