如何要求Servlet提供方法Java的实现

时间:2019-03-01 08:58:56

标签: java

对于这个行业的新手,我目前正在尝试开发一个处理各种形式的Web应用程序。在开发Web应用程序时,我注意到我正在向不同的servlet添加一种处理相似但功能不相同的功能的方法,现在知道在某些时候其他人可能正在寻找/对系统进行更改,我想通过抽象类为这些servlet创建一个模板,以便在添加新表单时系统代码保持一致

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    SampleMethodName(request,response);
}

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    SampleMethodName(request,response);
}

private void SampleMethodName(HttpServletRequest request, HttpServletResponse response) throws IOException {/* do stuff */}

我想为这些servlet创建一个抽象类作为模板,但是由于Java servlet已经扩展了一个抽象类,所以我不能这样做

public class SampleClassName extends HttpServlet {
private static final long serialVersionUID = 1L;

我觉得我需要改变方法,但是我还是想问

1 个答案:

答案 0 :(得分:0)

让一个抽象类扩展另一个抽象类没有问题。因此,您的特殊班级可能看起来像这样:

public abstract class AbstractSampleServlet extends HttpServlet {

  protected final void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    sampleMethodName(request, response);
  }

  protected abstract void sampleMethodName(HttpServletRequest request, HttpServletResponse response) throws IOException;

}

就是这样。现在,让所有实现者扩展您的新基类,而不是直接扩展HttpServlet。一些其他说明:

  • doGet应该标记为final,以便实现者不会意外覆盖它,从而绕过您的实现。
  • 抽象方法必须为publicprotected,但不能为private(如您的示例)。
  • 在Java中,通常的做法是让方法名以小写字母开头。