Servlet教程 (二) 实现Servlet的三种方式
Servlet核心的类和接口:
- Servlet接口
- GenericServlet抽象类
- HttpServlet类
- ServletConfig接口
- ServletRequest接口
- ServletResponse接口
Servlet类的层次结构
Servlet
↑继承
GenericServlet
↑继承
HttpServlet
按照Servlet类的层次结构,实现Servlet有三种方式:
1. 实现Servlet接口
实现Servlet接口,要实现所有接口的所有方法,
package com.etc.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletByInterface implements Servlet {
// ### 1. servlet销毁时调用的方法
public void destroy() {
}
public ServletConfig getServletConfig() {
return null;
}
public String getServletInfo() {
return null;
}
// ### 2. servlet初始化参数处理
public void init(ServletConfig arg0) throws ServletException {
}
// ### 3. 主要的方法,处理http请求
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
}
}
2. 继承GenericServlet类
继承GenericServlet只需要实现 service 方法,简化了Servlet编程
package com.etc.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletByGenericServlet extends GenericServlet {
// ### 1. 只要实现处理http请求的service方法
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
}
}
3. 继承HttpServlet类
HttpServlet类,实现了doGet,doPost等方法,可以对get和post请求做不同操作。
package com.etc.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletByHttpServlet extends HttpServlet{
// ### 1.处理GET请求
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
// ### 2.处理POST请求
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
}