該類定義一個普通的盾剩、依賴于協(xié)議的servlet雷激,如果要寫一個用于Web的HTTP servlet替蔬,擴展HpptServlet。
一個servlet可以直接擴展GenericServlet類屎暇,然而擴展一個指定協(xié)議的子類(如HttpServlet)顯得更為普遍
import javax.servlet.*;
import java.io.IOException;
//模擬GenericServlet
public class BServlet implements Servlet {
private ServletConfig config;
@Override
public void init(ServletConfig servletConfig) throws ServletException {
//吧tomcat傳遞的ServletConfig賦值給本類的一個成員承桥,其實就是他它保存起來,方便在其他方法中實現(xiàn)
this.config = servletConfig;
init();
}
public void init(){
System.out.println("hhhh ");
}
//這個方法肯定會在init之后調(diào)用
//init()被調(diào)用后根悼,本類成員this.config已經(jīng)有值了
@Override
public ServletConfig getServletConfig() {
return this.config;
}
@Override
public void service(ServletRequest servletRequest, ServletResponse servletResponse) throws ServletException, IOException {
System.out.println("每次請求都會被調(diào)用");
}
@Override
public String getServletInfo() {
return null;
}
@Override
public void destroy() {
}
//模擬實現(xiàn)如下方法凶异,在子類CServlet中調(diào)用
public ServletContext getServletContext() {
return config.getServletContext();
}
public String getServletName(){
return config.getServletName();
}
public String getInitParameter(String name){
return config.getInitParameter(name);
}
}
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
public class CServlet extends BServlet {
@Override
public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException {
String value = getInitParameter("p1");
}
@Override//組合的方式來繼承父類方法
public void init() {
System.out.println("哇---");
}
}