0
点赞
收藏
分享

微信扫一扫

Servlet技术原理和应用浅析


前言:近期在学习​​Spring​​​时,一直会提到一个名词​​Servlet​​,今天就来详解一下这门技术到底是什么。

​Servlet​​​是运行在​​web​​​服务端的​​Java​​​应用程序,他使用​​Java​​​语言编写,具有​​Java​​​语言的优点,与​​Java​​​程序的区别是,​​Servlet​​​对象主要封装了对​​HTTP​​​请求的处理,并且他的运行需要​​Servlet​​容器的支持。

​Servlet​​​是一个标准,他由​​Sun​​​定义,其具体细节由​​Servlet​​​容器进行实现,如​​Tomcat​​​、​​HBoss​​等。

Servlet技术原理和应用浅析_HTTP

  • ​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​​请求的。


举报

相关推荐

0 条评论