模拟Get请求和Post请求的分发
1)修改代码如下:
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
//System.out.println("我的第一个手写servlet");
//servletrequest对象强制转换为httpservletrequest对象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// get请求获取到"GET" ,post请求获取到"POST"字符串
String method = httpServletRequest.getMethod();
System.out.println("请求的方法为:"+method);
if("GET".equals(method)) {// 根据请求的方式 执行不同的方法去做不同的处理
doGet();
}else if("POST".equals(method)) {// 根据请求的方式 执行不同的方法去做不同的处理
doPost();
}
}
private void doPost() {
System.out.println("POST请求处理方法");
}
private void doGet() {
System.out.println("GET请求处理方法");
}
2)准备html页面表单内容如下(分别测试get请求和post请求):
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="http://localhost:8080/servletFirst/hello" method="post">
用户名:<input name="username" type="text" /><br />
密码:<input name="password" type="password" /><br />
<input type="submit" />
</form>
</body>
</html>
测试get请求的打印如下:
测试post请求的打印如下:
Servlet生命周期
servlet的生命周期。
什么时候创建一个servlet?
什么时候去销毁一个servlet?
Servlet的生命周期
1.先调用 Servlet的构造方法
2.调用 init 方法 初始化Servlet
3.调用 Servlet中的service方法处理请求操作
4.调用 destory方法 执行Servlet销毁的操作
init方法:当服务器创建一个serlvet的时候,会去调用init方法。
当我们第一次去访问一个servlet的时候,会去创建这个servlet对象。并且只会创建一次。
当我们继承HttpServlet类实现Servlet程序,重写init(Servletconfig config) 方法的时候,一定要在里面写上。super.init(config);
否则后面调用getServletContext()方法就会报空指针异常
@Override
publicvoidinit(ServletConfig config) throwsServletException {
super.init(config); // 一定要写上,因为在父类的方法中。这里保存了ServletConfig的引用
}
@Override
protectedvoid doGet(HttpServletRequestreq, HttpServletResponse resp) throwsServletException,
IOException {
getServletContext(); // 如果没有super.init(config)调用。这里就会报空指针异常
}