前言:近期在学习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
请求的。