Home  >  Q&A  >  body text

java - 重写HttpServlet的doGet、doPost方法时为什么要把它们的访问权限设为public?

看一本Java Web入门书时,其中提到HttpServlet的doGet方法是protected的,我们重写doGet方法时,为了使其能被Servlet容器访问,应该把访问权限设为public,然后我看网上的例子也全是把doGet写成public。Servlet容器为什么会直接访问doGet方法?HttpServlet的原理不是容器调用其service()方法,其service()根据实际的请求方法来调用doGet或者doPost的么。

高洛峰高洛峰2743 days ago959

reply all(2)I'll reply

  • PHPz

    PHPz2017-04-18 10:54:23

    Which open source project have you seen written doGetdoPost是用public? At least I haven't seen it.

    The scope of action should be as small as possible (can be used private的就不要用protected,能用protected的就不要用public). This is a principle that needs to be followed in coding.

    reply
    0
  • 迷茫

    迷茫2017-04-18 10:54:23

    Access the service method first, and then use the service method to determine whether to use the doget or dopost method. However, the servlet we wrote inherits HttpServlet and rewrites the doget and doPost of the parent class, so we must use public. Java designed this method of increasing permissions so that subclasses can decide whether their methods can be opened to callers. If the subclass is protected, the servlet container can also access it. Generally, the access permissions for overridden parent class methods are >= the parent class's methods.

    reply
    0
  • Cancelreply