image.pngimage.png
    继承子类,调用封装类, 重写和父类相同的方法

    1. package com.itheima.web;
    2. import javax.servlet.*;
    3. import javax.servlet.annotation.WebServlet;
    4. import javax.servlet.http.HttpServletRequest;
    5. import java.io.IOException;
    6. @WebServlet("/demo5")
    7. public class ServletDemo5 extends MyHttpServlet { // 子类继承父类,当子类的父类方法一样时要重写
    8. @Override
    9. protected void doGet(ServletRequest req, ServletResponse res) {
    10. System.out.println("get...");
    11. }
    12. @Override
    13. protected void doPost(ServletRequest req, ServletResponse res) {
    14. System.out.println("post");
    15. }
    16. }

    定义一个封装类(继承父类)

    1. package com.itheima.web;
    2. import javax.servlet.*;
    3. import javax.servlet.http.HttpServletRequest;
    4. import java.io.IOException;
    5. /**
    6. * 定义一个继承父类,让别的类继承,并重写它的方法(子类和自己父类的方法一样时要重写)
    7. */
    8. public class MyHttpServlet implements Servlet {
    9. @Override
    10. public void init(ServletConfig servletConfig) throws ServletException {
    11. }
    12. @Override
    13. public ServletConfig getServletConfig() {
    14. return null;
    15. }
    16. @Override
    17. public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
    18. // 根据请求方式的不同,进行分别的处理
    19. HttpServletRequest request = (HttpServletRequest) req;
    20. // 1. 获取请求方式:
    21. String method = request.getMethod();
    22. // 2. 判断
    23. if ("GET".equals(method)) {
    24. // get方式的处理逻辑
    25. doGet(req,res);
    26. } else if ("POST".equals(method)) {
    27. // post方式的处理逻辑
    28. doPost(req,res);
    29. }
    30. }
    31. protected void doPost(ServletRequest req, ServletResponse res) {
    32. }
    33. // protected 权限修饰符表示子类可以看到这个方法
    34. protected void doGet(ServletRequest req, ServletResponse res) {
    35. }
    36. @Override
    37. public String getServletInfo() {
    38. return null;
    39. }
    40. @Override
    41. public void destroy() {
    42. }
    43. }