Servlet简介
Servlet是运行在web容器上的小程序。这种程序使用Java编程语言实现。在通信量大的服务器上,Servlet的优点在于它们的执行速度快于CGI程序,各个用户请求被激活成单个程序中的一个线程,而无需创建单独的进行,这意味着服务器端处理请求的系统开销明显降低。
Servlet生命周期
服务器收到客户端的请求后:
1.web容器判断相应的Servlet类是否已加载到内存,并创建了该Servlet的实例。如果是,则转到第4步,否则第2步;
2.加载并创建该Servlet类的一个实例对象;
3.调用Servlet实例对象的init()方法;
4.创建一个用于封装HTTP请求消息的HttpServletRequest对象和一个代表HTTP响应的HttpServletResponse对象,然后调用servlet的service()方法并将这两个对象做为参数传递;
5.web容器被停止或是重启之前,调用Servlet的Destroy()方法消毁实例对象。
所有的servlet需要继承于HttpServlet类,需要重写其doGet和doPost方法。
package servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Cart */ @WebServlet("/Cart") public class Cart extends HttpServlet { private static final long serialVersionUID = 1L; private String action; /** * @see HttpServlet#HttpServlet() */ public Cart() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { if (request.getParameter("action") != null) { this.action = request.getParameter("action"); if (this.action.equals("add")) { this.addToCart(request, response); } else if (this.action.equals("remove")) { this.removeFromCart(request, response); } else if (this.action.equals("list")) { this.showCart(request, response); } } } protected void addToCart(HttpServletRequest request, HttpServletResponse response) { Integer itemId = Integer.parseInt(request.getParameter("itemId")); } protected void showCart(HttpServletRequest request, HttpServletResponse response) { } protected void removeFromCart(HttpServletRequest request, HttpServletResponse response) { } }
写好一个Servlet类之后,需要在位于WEB-INF目录下的web.xml文件中将其注册。
注册一个servlet需要以下两做代码,第一个是要将servlet类注册到系统中,第二个则是将servlet的方问路径注册到系统中,这里需要注意的是在url-pattern中一定要是以"/"开始,否则会提示404错误。
<servlet> <servlet-name>SERVLET NAME</servlet-name> <servlet-class>SERVLET CLASS NAME INCLUDED PACKAGE NAME</servlet-class> <servlet> <servlet-mapping> <servlet-name>SERVLET NAME</servlet-name> <url-pattern>/ACCESS PATH</url-pattern> </servlet-mapping>
原文地址:http://blog.csdn.net/chris_mao/article/details/45042735