Servlet是用Java代码编写的服务器方软件程序,用于处理客户机和服务器之间的消息传递。Java Servlet API为请求和响应消息定义了一个标准接口,这样Servlet就可以跨平台和跨不同的Web应用服务器间移植。
Servlet可以通过动态构造一个发回客户机的响应来响应客户机请求。例如:下面是一个响应HTTP请求的Servlet.源代码如下:
package com.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServlet extends HttpServlet {
public HelloServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out
.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method and say you hello");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
public void doPut(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Put your code here
}
public void init() throws ServletException {
// Put your code here
}
}
在Web.xml配置文件的配置如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<description>
This is the description of my J2EE component
</description>
<display-name>
This is the display name of my J2EE component
</display-name>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>
</web-app>
在浏览器里输入:
http://localhost:818/beike/servlet/HelloServlet
运行结果如下图
由于Servlet是用Java编程语言编写的,它们可以访问整个Java API集合。这就使它们非常适合实现复杂的商业应用逻辑,特别是访问企业中其它位置的数据。Java Database Connection(JDBC) API就是一个示例,它允许Java程序访问关系数据库。一般我们不直接在Servelt里面写JDBC编程,而是通过连接池技术或者Hibernate技术来实现JDBC的连接,后面会有综合的例子。由于没有与Servlet关联的图形,因此它不适合访问GUI Java API(AWT/Swing)
可以多次调用一个Servlet来响应来自多个客户机的请求。这是一种多线程的工作方式,该Servlet只有一个实例,多个用户通过多线程的访问,来响应给客户的。因此,一个Servlet可以同时处理多个请求,并且可以使这些请求同步。Servlet可以将请求转发到其它服务器和Servlet.