java - 重写HttpServlet的doGet、doPost方法时为什么要把它们的访问权限设为public?
高洛峰
高洛峰 2017-04-18 10:52:23
0
2
1007

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

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(2)
PHPzhong

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.

迷茫

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.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template