4、Servlet
Java Servlet 是运行在 Web 服务器或应用服务器上的程序,它是作为来自 Web 浏览器或其他 HTTP 客户端的请求和 HTTP 服务器上的数据库或应用程序之间的中间层。
public class StudentInfoServlet implements Servlet {
//初始化
@Override
public void init(ServletConfig config) throws ServletException {
}
//获取配置
@Override
public ServletConfig getServletConfig() {
return null;
}
//主要服务
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
}
//获取服务信息
@Override
public String getServletInfo() {
return null;
}
//销毁
@Override
public void destroy() {
}
}
Servlet的主要方法是service,可以在service进行主要的操作,所以后面就做了更多的简化操作
public class StudentInfoServlet extends GenericServlet{
@Override
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
}
}
继承了GenericServlet ,我们只要关注service方法就可以了,后面又做了更多的优化,特别是在get和post请求上。
public class StudentInfoServlet extends HttpServlet{
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
}
}
根据请求是GET和POST等,选择性重写doGet()或doPost方法,处理请求依然是调用service()方法,但是service()方法会根据请求类型区调用doGet()方法和doPost()方法。
不管是以何种方法创建Servlet类,都是直接或间接实现了Servlet,在springboot中,controller就是一个servlet请求
4、生命周期
servlet生命周期三个方法:
-
init()初始化阶段(只可执行1次)
-
service()处理客户端请求阶段(可执行多次)
-
destroy()终止阶段(只可执行1次)
同时注意一点,servlet是非线程安全的。

浙公网安备 33010602011771号