Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

你见过哪个开源项目写doGetdoPost是用public的?至少我没见过。

作用范围要尽量小(能用private的就不要用protected,能用protected的就不要用public),这是编码中需要遵循的一个原则。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...