2012-02-22 4 views
1

저는 Java로 블로그를 작성했습니다. 이제는 서블릿 모델이 2 개 있습니다. 먼저 기사로 조작하는 함수를 작성하고 두 번째로 카테고리로 조작하십시오. 새 기사를 추가 할 때 양식의 드롭 다운 목록에 모든 범주가 ​​있어야합니다. 내 서블릿 ArticleMod에서 이미 CategoryMod 서블릿에 배치 된 getCategoryList()를 호출 할 수 있습니다.다른 서블릿의 함수 호출

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; 
    } 

이 서블릿 메신저에 내가 다른 서블릿에서 해당 함수를 호출 할 수있는 방법이

 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) { 
       } 
    } 

처럼 사용

다음 기능의 코드는?

답변

1

두 개의 서블릿에 대해 상위 추상 클래스를 사용하고 공유 동작을 배치 할 수 있습니다. 샘플 코드 다음을 참조하십시오

이 방법은 그들이 Parent을 가질 수있는 동작을 공유
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(); 
    } 
} 

, 그것은 OOP의 규칙입니다.

+0

내 서블릿은 모두 HttpServlet 클래스의 하위 클래스이며 하나의 서블릿은 두 개의 병렬 클래스로 구성된 하위 클래스 일 수 있습니까? 아니면 HttpServlet에 의해 제너럴 클래스를 확장하고 일반 클래스로 ServletMods를 확장해야합니까? –

+0

위의 샘플을 직접 작성합니다. 보시면'HttpServlet'을 확장 한'Parent' 클래스와'Parnet'을 확장 한'childs' 클래스가 있다는 것을 이해하게 될 것입니다. – MJM

+0

미안하다, 보지 못했다 ... 고마워, D –

3

두 서블릿의 공통 기본 클래스 또는 두 서블릿이 공유 할 수있는 유틸리티 클래스로 메소드를 이동하십시오. 두 서블릿을 서로 임의적으로 의존하도록 작성하는 것은 나쁜 설계 일 것입니다.