Servelet 简介
我们可以实现 Servlet接口:
package com.LearnJAVA.Serverlet; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class helloServlet */ @WebServlet("/hello") public class helloServlet implements Servlet { private static final long serialVersionUID = 1L; public helloServlet () { System.out.println("constructor"); } @Override public void destroy() { // TODO Auto-generated method stub System.out.println("destroy"); } @Override public ServletConfig getServletConfig() { // TODO Auto-generated method stub return null; } @Override public String getServletInfo() { // TODO Auto-generated method stub return null; } @Override public void init(ServletConfig arg0) throws ServletException { // TODO Auto-generated method stub System.out.println("init..."); } @Override public void service(ServletRequest arg0, ServletResponse arg1) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("service.."); } }
Servlet被Servlet容器管理,其生命周期:
1 构造器: 只被调用一次,创建servlet实例. 所以servlet是单实例的.(有线程安全问题)
2 init : 只被调用一次,在servlet被创建之后调用,用于初始化servelet.
3 service: 每次请求时调用,用于响应请求
4 destroy :服务器关闭时调用,用于销毁servlet,释放资源
5 load-on-startup 参数:
当其值大于等于0时, 在启动web项目时,调用servlet构造器和init方法,且值越小越先创建
当其值小于0时,在第一次请求时创建