【Servlet】继承关系以及service方法

本文详细介绍了Servlet中的继承关系,重点讲解了GenericServlet和HttpServlet的关系,以及Servlet接口的关键方法如init(),service(),destroy()和doPost()的使用和实现。特别强调了doPost方法的重写和HTTP方法处理。
摘要由CSDN通过智能技术生成

一、继承关系

Servlet接口下有一个GenericServlet抽象类。在GenericServlet下有一个子类HttpServlet,它是基于http协议。

继承关系


javax.servlet.Servlet接口

​		javax.GenericServlet抽象类

​			javax.servlet.http.HttpServlet

二、相关方法

javax.servlet.Servlet接口

  1. void init(config) - 初始方法

  2. void service(request, response) - 服务方法

    当发请求过来时,service方法会被自动调用。(其实是tomcat容器调用的)

  3. void destroy() - 销毁方法

javax.GenericServlet抽象类中service方法仍然是抽象的,但init()和destroy()方法已经实现

image-20240401103328936

javax.servlet.http.HttpServlet实现了service方法

protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getMethod(); // 获取请求的方式
        long lastModified;
        // 各种if判断,根据请求方式不同,决定去调用不同的do方法
    	// 在HttpServlet中这些do方法默认都是405的实现风格-要我们子类去实现对应的方法,否则默认会报405错误
    	// 因此,我们在新建Servlet时,我们才会去考虑请求方法,从而决定重写哪个do方法
        if (method.equals("GET")) { // 如果发过来的是GET请求
            ...
        } else if (method.equals("HEAD")) {
            lastModified = this.getLastModified(req);
            this.maybeSetLastModified(resp, lastModified);
            this.doHead(req, resp);
        } else if (method.equals("POST")) {
            this.doPost(req, resp);
        } else if (method.equals("PUT")) {
            this.doPut(req, resp);
        } else if (method.equals("DELETE")) {
            this.doDelete(req, resp);
        } else if (method.equals("OPTIONS")) {
            this.doOptions(req, resp);
        } else if (method.equals("TRACE")) {
            this.doTrace(req, resp);
        } else {
            String errMsg = lStrings.getString("http.method_not_implemented");
            Object[] errArgs = new Object[]{method};
            errMsg = MessageFormat.format(errMsg, errArgs);
            resp.sendError(501, errMsg);
        }
    }

查看doPost方法,如果我们继承HttpServlet的类没有重写HttpServlet的doPost请求,它就会调用父类(HttpServlet)的doPost方法,直接报405错。

在HttpServlet这个抽象类中,do方法基本都差不多。

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String protocol = req.getProtocol(); // 获取http协议
        String msg = lStrings.getString("http.method_post_not_supported"); // 它会根据http.method_post_not_supported字符串去找另一个字符串,所对应的value值就是消息
        if (protocol.endsWith("1.1")) {
            resp.sendError(405, msg); // 报405错,然后把msg显示出来
        } else {
            resp.sendError(400, msg);
        }
    }
  • 5
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值