servlet的实质:浏览器发送一个http请求,web容器会自动分配一个特定的servlet对该http请求进行处理,servlet的本质其实就是一个Java对象,而该对象拥有很多方法来处理http请求。常见方法有doPose()和doGet()等。web容器中有很多个servlet,发送过来的特定的http请求由哪个servlet处理,是由web容器中的web.html来决定的。
servlet的生命周期:Servlet 生命周期:Servlet 加载--->实例化--->服务--->销毁。
当没有在web.xml文件中设置<load-on-startup>时,init()会在网页加载的时候调用,当在web.xml中设置了<load-on-startup>时,init()会在restart服务器的时候调用。
- init():在Servlet的生命周期中,仅执行一次init()方法。它是在服务器装入Servlet时执行的,负责初始化Servlet对象。可以配置服务器,以在启动服务器或客户机首次访问Servlet时装入Servlet。无论有多少客户机访问Servlet,都不会重复执行init()。
- service():它是Servlet的核心,负责响应客户的请求。每当一个客户请求一个HttpServlet对象,该对象的Service()方法就要调用,而且传递给这个方法一个“请求”(ServletRequest)对象和一个“响应”(ServletResponse)对象作为参数。在HttpServlet中已存在Service()方法。默认的服务功能是调用与HTTP请求的方法相应的do功能。
- destroy(): 仅执行一次,在服务器端停止且卸载Servlet时执行该方法。当Servlet对象退出生命周期时,负责释放占用的资源。一个Servlet在运行service()方法时可能会产生其他的线程,因此需要确认在调用destroy()方法时,这些线程已经终止或完成。
servlet程序代码:public class MyServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
public MyServlet2() {
System.out.println("构造方法");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String name=request.getParameter("username");
String ps=request.getParameter("password");
PrintWriter out=response.getWriter();
if("zhangsan".equals(name) && "hello".equalsIgnoreCase(ps)){
out.print("succeed");
}else{
out.print("sorry!");
}
}
@Override
public void service(ServletRequest arg0, ServletResponse arg1)
throws ServletException, IOException {
System.out.println("为人民服务");
}
@Override
public void destroy() {
System.out.println("我去见上帝了");
}
@Override
public void init() throws ServletException {
System.out.println("我降临人间了");
}
}
index.jsp文件中代码:<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!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>Login</title>
</head>
<body>
<form action="http://localhost:8080/Web/demo1" method="post">
用户名:<input type="text" name="username" width="300px" height="200px">
<br>
密码:<input type="password" name="password" width="300px" height="200px">
<br>
<input type="submit" value="提交">
<br>
</form>
</body>
</html>
web.xml文件中添加代码:<servlet-mapping>
<servlet-name>demo1</servlet-name>
<url-pattern>/demo1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>demo1</servlet-name>
<servlet-class>com.serlvet.MyServlet2</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>