- servlet生命周期:实例化,初始化,服务,销毁
- servlet中的初始化方法有两个:init(),init(config),有参数的init后面也会调用无参init
- 其中带参数方法代码如下
public void init(ServletConfig config){
this.config = config;
} - 另一个无参的就是public void init(){}
- 如果我们想要在Servlet初始化中完成一下工作,那么我们可以重写init方法,在init方法通过如下步骤去获取初始化设置的的数据
- 获取config对象:ServletConfig config = getServletConfig();
- 编写配置文件或者使用注解@webservlet中的initParameter
- 格式参照下面
-
@WebInitParam(name="hello",value = "world"), @WebInitParam(name = "uname",value = "jim") })```
- 如果是web中xml文件配置
-
<servlet-name>AppServlet</servlet-name> <servlet-class>Application</servlet-class> <init-param> <param-name>hello</param-name> <param-value>world</param-value> </init-param>
- 获取初始化参数值:config.getInitParameters(key);
- 其中带参数方法代码如下
- 学习Servlet中的ServletContext和
<context-param>
- 获取ServletContext,有很多种方法
- 在init()中,通过 ServletContext context = config.getServletContext
- 在service()中,通过 request.getServletContext
- 在session中,通过 session.getServletContext
- 以上三个都会获取到同一个ServletContext,[[ServletContext]] 范围更大的session,和application同一个概念
- 获取初始化值 context.getInitParamete();
- 获取ServletContext,有很多种方法
- [[context-param与init-param]]这两者之间是有区别的
9 servlet2
最新推荐文章于 2024-09-15 19:46:31 发布