java Web应用程序开发(Servlet知识)

Servlet生命周期

web容器调用Servlet处理请求过程(图文描述)
在这里插入图片描述

总结servlet生命周期
1,servlet容器收到请求之后,就会创建一个servlet,并且针对客户端的多次请求,也只会创建一个servlet。
2,实例化完成之后, Web容器回调init()方法,init()方法一生只能调用一次。
3 ,Web容器启动一个线程,在线程中回调service方法service方法中根据请求方式来调用不同的处理方法(doGet或doPost)
4,Web容器回调destroy()方法(死亡)
代码描述
public class Servlet01 extends HttpServlet {

public Servlet01() {

}

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// TODO Auto-generated method stub
	//System.out.println("doGet方法");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// TODO Auto-generated method stub
	System.out.println(4);
}

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	// TODO Auto-generated method stub
	/*String ert = req.getMethod();
	System.out.println("哈哈" + ert);
	if (ert.equals("GET")) {
		doGet(req, resp);
	} else {
		doPost(req, resp);*/

	}
//}

@Override
public void destroy() {
	// TODO Auto-generated method stub
	System.out.println("死亡");
}

@Override
public void init(ServletConfig config) throws ServletException {
	// TODO Auto-generated method stub
	//System.out.println("第一");
}

}

Servlet的回调方法
Servlet是一个要被容器调用的组件类,它的运行过
程由Servlet容器控制和调度。所以,Servlet接口中
定义的所有方法都是回调方法。

回调方法是指供系统调用的方法。
获取客户端传递的请求参数
public void setCharacterEncoding(String charsetName) 设置请求消息体的编码字符集。(对get传递的数据无效)
public String getParameter(String name) –返回指定名称参数的字符串值
public String[] getParameterValues(String name) – 返回指定名称参数的所有字符串值数组。适用于复选框多选列表。
public java.util.Enumeration getParameterNames() – 返回一个包含请求消息中的所有参数名的Enumeration对象
public java.util.Map getParameterMap() – 返回一个将请求消息中的所有参数名和值的Map对象。
key是参数名(String),value是所对应的字符串值数组。

猜你喜欢

转载自blog.csdn.net/slh20030904/article/details/85061069