生命周期
可以第一次请求时就实例化,也可以web容器启动时就实例化
WebServlet(loadOnStartUp=1)
<loadOnStartUp.../>
直接收整型值,越小优先级越高
完整配置实例
annotation:
1 @WebServlet(name = "testServletAnnotation", urlPatterns = { "/testservletannotation/*","/asd/*" }, initParams = { @WebInitParam(name = "a", value = "aaa") }) 2 public class testServletAnnotation extends HttpServlet { 3 private static final long serialVersionUID = 1L; 4 @SuppressWarnings("unused") 5 private ServletConfig config; 6 7 public void init(ServletConfig config) throws ServletException { 8 this.config = config; 9 } 10 11 public void service(HttpServletRequest request, HttpServletResponse response) 12 throws ServletException, IOException { 13 request.setCharacterEncoding("utf-8"); 14 response.setContentType("text/html;charSet=utf-8"); 15 HttpSession session = request.getSession(); 16 ServletContext cxt = request.getServletContext(); 17 cxt.setAttribute("hate", "Deep hating!"); 18 PrintStream out = new PrintStream(response.getOutputStream()); 19 String a = config.getInitParameter("a"); 20 out.println("just a servlet test! <br /> @annotation依然有效! <br /> "); 21 out.println("session:" + session.getAttribute("love")+"<br />"); 22 out.println("a:" + a); 23 } 24 25 }
XML:
1 <servlet> 2 <servlet-name>testServletXml</servlet-name> 3 <servlet-class>servlet.testServletXml</servlet-class> 4 </servlet> 5 <servlet-mapping> 6 <servlet-name>testServletXml</servlet-name> 7 <url-pattern>/testservletxml</url-pattern> 8 </servlet-mapping>
获取Servlet配置参数
Annotation配置
1 @WebServlet(name = "testServletAnnotation", urlPatterns = { "/testservletannotation/*","/asd/*" }, initParams = { @WebInitParam(name = "a", value = "aaa") }) 2 2 3 3 4 4 ServletContext cxt = request.getServletContext(); 5 5 6 6 7 7 out.println("a:" + a);
xml参数配置
1 <init-param> 2 <param-name>a</param-name> 3 <param-value>aaa</param-value> 4 </init-param>