继承子类,调用封装类, 重写和父类相同的方法
package com.itheima.web;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
@WebServlet("/demo5")
public class ServletDemo5 extends MyHttpServlet { // 子类继承父类,当子类的父类方法一样时要重写
@Override
protected void doGet(ServletRequest req, ServletResponse res) {
System.out.println("get...");
}
@Override
protected void doPost(ServletRequest req, ServletResponse res) {
System.out.println("post");
}
}
定义一个封装类(继承父类)
package com.itheima.web;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
/**
* 定义一个继承父类,让别的类继承,并重写它的方法(子类和自己父类的方法一样时要重写)
*/
public class MyHttpServlet implements Servlet {
@Override
public void init(ServletConfig servletConfig) throws ServletException {
}
@Override
public ServletConfig getServletConfig() {
return null;
}
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
// 根据请求方式的不同,进行分别的处理
HttpServletRequest request = (HttpServletRequest) req;
// 1. 获取请求方式:
String method = request.getMethod();
// 2. 判断
if ("GET".equals(method)) {
// get方式的处理逻辑
doGet(req,res);
} else if ("POST".equals(method)) {
// post方式的处理逻辑
doPost(req,res);
}
}
protected void doPost(ServletRequest req, ServletResponse res) {
}
// protected 权限修饰符表示子类可以看到这个方法
protected void doGet(ServletRequest req, ServletResponse res) {
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
}