一、Servlet生命周期中的方法
因为Servlet中没有main()方法,不能独立运行,其运行主要靠Tomcat服务器控制和调度。
生命周期:指的是ServletContext中何时创建Servlet容器,调用其doGet()、doPost()等做出请求、响应的方法,何时进行销毁其实例的方法。
1、init (ServletConfig config),在 Servlet 实例创建之后执行
public void init(ServletConfig config) throws ServletException {
System.out.println("实例创建了Servlet");
}
2、service ( ServletRequest req, ServletResponse res)方法,由 Servlet 容器调用,用来处理客户端的请求
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
System.out.println("服务调用了Service()方法");
}
doGet()方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
doPost()方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//调用doGet方法才会起作用,统一处理
doGet(request, response);
}
3、destroy ( )由 Servlet 容器调用,释放Servlet对象所使用的资源,销毁Servlet对象
public void destroy() {
System.out.println("实例销毁了Servlet对象");
}
二、request请求中的方法
1、setCharacterEncoding (String charset )、设置请求体的字符编码