前言:近期在学习Spring时,一直会提到一个名词Servlet,今天就来详解一下这门技术到底是什么。
Servlet是运行在web服务端的Java应用程序,他使用Java语言编写,具有Java语言的优点,与Java程序的区别是,Servlet对象主要封装了对HTTP请求的处理,并且他的运行需要Servlet容器的支持。
Servlet是一个标准,他由Sun定义,其具体细节由Servlet容器进行实现,如Tomcat、HBoss等。

-
Serializable是java.io包的序列化接口。 -
Servlet和ServletConfig是javax.servlet中的对象。 -
GenericServlet分别实现了上述三个接口。 -
HttpServlet为HTTP请求中POST和GET等等提供; 具体的操作方法。
技术特点:功能强大、可移植、性能高效、安全性高、可扩展。
Servlet代码结构
在Java中,通常所说是Servlet是指HttpServlet对象,在声明一个对象为Servlet时,需要集成HttpServlet类,HttpServlet类是Servlet接口的一个实现类,继承该类后,可以重写HttpServlet类中的方法对HTTP请求进行处理。
以下为javax.servlet.http.HttpServlet中部分代码,该类主要处理HTTP请求
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// GET请求
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// POST请求
}
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// PUT请求
}
protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// DELETE请求
}以下为javax.servlet.GenericServlet类中代码,主要负责Servlet的一些整体工作。
public void init(ServletConfig config) throws ServletException {
this.config = config;
this.init();
}
public void init() throws ServletException {
// Servelt初始化生命周期
}
public void destroy() {
// Servlet生命周期结束
}总而言之,Servlet可以看做是一个中间件,是用来专门处理HTTP请求的。










