1.servlet定义: 运行在服务器端的java类.
2.servle生命周期
? ?<1>WEB容器创建Servlet实例
? ?<2>调用Servlet的init方法
? ?<3>多次调用Servlet的service方法(即Servlet是单例的)
? ?<4>WEB容器关闭时调用Servlet的destroy方法销毁Servlet
?
?
class="java"><?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <context-param> <param-name>test2</param-name> <param-value>myServlet2</param-value> </context-param> <servlet> <servlet-name>MyServlet</servlet-name> <servlet-class>com.wr.servlet.MyServlet</servlet-class> <init-param> <param-name>test</param-name> <param-value>myServlet</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>MyServlet</servlet-name> <url-pattern>/MyServlet</url-pattern> </servlet-mapping> </web-app>
? ??
? ??monospace; line-height: 1.5; background-color: #fafafa;">load-on-startup: 配置Servlet的加载方式
? ? ? ? ? ? <1>值为负数时,访问当前Servlet时才创建Servlet实例
? ? ? ? ? ? <2>值位正数时,WEB应用加载时就创建Servlet实例, 值越小优先级越高,最先创建.
?
package com.wr.servlet; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; /** * Servlet implementation class MyServlet */ public class MyServlet implements Servlet{ public MyServlet() { System.out.println("MyServlet.MyServlet()"); } public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub System.out.println("MyServlet.init()"); String param = config.getInitParameter("test"); System.out.println(param); ServletContext context = config.getServletContext(); System.out.println(context.getInitParameter("test2")); } public ServletConfig getServletConfig() { // TODO Auto-generated method stub System.out.println("MyServlet.getServletConfig()"); return null; } public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException { System.out.println("MyServlet.service()"); // TODO Auto-generated method stub } public String getServletInfo() { System.out.println("MyServlet.getServletInfo()"); // TODO Auto-generated method stub return null; } public void destroy() { System.out.println("MyServlet.destroy()"); // TODO Auto-generated method stub } }
??? ?ServletConfig: 当前Servlet的配置对象, 可以读取配置在Servlet中的初始化参数
? ? ?ServletContext: 当前WEB应用的上下文对象, 可以读取配置在WEB配置文件中的初始化参数