Servlet细节:HttpServlet和一些开发细节&Servlet被外界访问的配置&同一Servlet映射到多个url&缺省servlet

一、Servlet接口,sun公司已经定义了两个默认实现类,GenericServlet和HttpServlet。

HttpServlet指的是能处理http请求的Servlet,在原有的Servlet接口上添加了一些http协议处理方法,比Servlet的接口功能更为强大,因此在编写Servlet的时候,通常应该继承这个类,而不是直接实现Servlet接口。

HttpServlet在实现Servlet接口的时候,覆写了service方法,该方法体内的代码互自动判断用户的请求方式,如果是get请求,就会调用HttpServlet里的doGet方法,如果是Post请求,就会调用doPost方法,因此在开发的时候,通常只需要覆写doGet方法或doPost方法,而不需要覆写service方法。

在api文档中,也已经说明了建议:

Provides an abstract class to be subclassed to create an HTTP servlet suitable for a Web site. **A subclass of HttpServlet must override at least one method, usually one of these:

    • doGet, if the servlet supports HTTP GET requests
    • doPost, for HTTP POST requests
    • doPut, for HTTP PUT requests
    • doDelete, for HTTP DELETE requests
    • init and destroy, to manage resources that are held for the life of the servlet
    • getServletInfo, which the servlet uses to provide information about itself

There’s almost no reason to override the service method. service handles standard HTTP requests by dispatching them to the handler methods for each HTTP request type (the doXXX methods listed above).
Likewise, there’s almost no reason to override the doOptions and doTrace methods.
没必要重写那几个方法,有必要重写的只有建议的六个方法。
我们还在上一个自己写的Servlet里面来创建一个新的Servlet例子,平行于servDemo新建另一个Servlet文件。
在新建的时候我们不选择class文件而选择直接new一个Servlet,这时候里面会让我们选择要继承的父类等等信息,要重写的方法等等。

@WebServlet("/servletDemo2")
public class servletDemo2 extends HttpServlet {
     private static final long serialVersionUID = 1L;
    public servletDemo2() {
        super();
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值