标签:
Servlet是一个运行在web服务器上的小的Java程序,它通过接收和响应web客户端的请求,在tomcat服务器中有已经帮我们实现好了Servlet接口的实现类:javax.servlet.GenericServlet和javax.servlet.http.HttpServlet类,我们只需重写其方法即可。关于ServletAPI的介绍如下:
public interface Servlet
Defines methods that all servlets must implement.
A servlet is a small Java program that runs within a Web server. Servlets receive and respond to requests from Web clients, usually across HTTP, the HyperText Transfer Protocol.
To implement this interface, you can write a generic servlet that extends javax.servlet.GenericServlet or an HTTP servlet that extends javax.servlet.http.HttpServlet.
This interface defines methods to initialize a servlet, to service requests, and to remove a servlet from the server. These are known as life-cycle methods and are called in the following sequence:
The servlet is constructed, then initialized with the init method.
Any calls from clients to the service method are handled.
The servlet is taken out of service, then destroyed with the destroy method, then garbage collected and finalized.
其中与生命周期相关的方法(life-cycle methods)指的是在其创建到销毁过程中一定会执行的方法,如init()、service()以及destroy() 方法。
例1:
我们首先创建一个FirstServlet:
package com;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class FirstServlet extends GenericServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
@Override
public void service(ServletRequest req, ServletResponse
res)throws ServletException, IOException {
OutputStream out=res.getOutputStream();
out.write("Hello Servlet!".getBytes());
}
}
然后在web.xml中配置FirstServlet的映射关系:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>FirstServlet</servlet-name>
<servlet-class>com.FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FirstServlet</servlet-name>
<url-pattern>/FirstServlet</url-pattern>
</servlet-mapping>
</web-app>
最后把应用部署到Tomcat服务器上,用浏览器访问http://localhost:8080/TestServlet/FirstServlet 即可显示Hello Servlet!
其调用图如下:
注:可能由于编辑器的缺陷,此时序图在浏览器下显示不完整
需要注意一点的是,只有在首次访问服务器才会创建目标Servlet,此后该目标Servlet一直驻留在内存中,直到关闭服务器,调用destroy()方法。
标签:
原文地址:http://blog.csdn.net/u010999240/article/details/44318513