Web学习笔记2
六、Servlet 的生命周期
1、当浏览器访问 Servlet 的时候,Tomcat 会查询当前 Servlet 的实例化对象是否存在,如果不存在,则通过反射机制动态创建对象,如果存在,直接执⾏service ⽅法。这就类似于字符串常量池。为的就是节省内存开销。
2、调⽤ init() ⽅法完成初始化操作。
3、调⽤ service() ⽅法完成业务逻辑操作。
4、关闭 Tomcat 时,会调⽤ destory() ⽅法,释放当前对象所占⽤的资源。
注:其中Tomcat,借助反射机制,来调用类的无参构造器,来完成该类对象的创建。
七、Servlet 的生命周期方法
⽆参构造函数、init()、service()、destory()
1、⽆参构造函数只调⽤⼀次,创建对象。
2、init()方法 只调⽤⼀次,初始化对象。
3、service()方法 调⽤ N 次,执⾏业务⽅法。
4、destory()方法 只调⽤⼀次,卸载对象。
八、Servlet初始化方法init()中的ServletConfig接口
- 该接⼝是⽤来描述 Servlet 的基本信息的。
2. ServletConfig接口中的方法:
(1)getServletName(): 返回 Servlet 的名称,全类名(带着包名的类名)
(2)getInitParameter(String key): 获取 init 参数的值
(前提:必须使用web.xml配置,不能使用注解配置)
(3)getInitParameterNames(): 返回所有的 initParamter 的 name 值,⼀般⽤作遍历初始化参数
(4)getServletContext():返回 ServletContext 对象,它是 Servlet 的上下⽂,整个 Servlet 的管理者。其中ServletContext也是一个接口,该接口中常用的方法为:getContextPath()。
3. ServletConfig 和 ServletContext 的区别:
(1)ServletConfig 作⽤于某个 Servlet 实例,每个 Servlet 都有对应的ServletConfig,ServletContext 作⽤于整个 Web 应⽤,⼀个 Web 应⽤对应⼀个 ServletContext,多个 Servlet 实例对应⼀个ServletContext。
(2)ServletConfig 是局部对象,ServletContext 是全局对象。
(3)Config:n. 配置,布局
(4)Context:n. 背景,环境
九、Servlet 的层次结构
1. Servlet的层次
一般我们继承HttpServlet类即可。因为更为方便。自己实现Servlet的接口,那么客户端Get和Post都由service()方法来处理。而继承HttpServlet类,这可以单独处理post和get请求。只需要重写两个方法:doGet()、doPost()方法。
@WebServlet("/test")
public class testServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应的类型
resp.setContentType("text/html;charset=UTF-8");
//服务器对客户端的相应
resp.getWriter().write("返回get");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置响应的类型
resp.setContentType("text/html;charset=UTF-8");
//服务器对客户端的相应
resp.getWriter().write("返回post");
}
}
用Postman测试如下:
GenericServlet 实现 Servlet 接口,同时为它的子类屏蔽了不常⽤的方法,⼦类只需要重写 service 方法即可。HttpServlet 继承GenericServlet,根据请求类型进行分发处理,GET 进⼊ doGET ⽅法,POST 进⼊doPOST ⽅法。开发者⾃定义的 Servlet 类只需要继承 HttpServlet 即可,重新 doGET 和 doPOST。
2. HTTP 请求有很多种类型,常用的有四种:
(1)GET 读取
(2)POST 保存
(3)PUT 修改
(4)DELETE 删除。
数据库也是有CRUD操作,都是与此类似,增删改查。
笔记部分来自韩顺平老师