servlet类中定义的成员变量,被所有的客户线程共享。
要求利用servlet共享变量实现计数器功能。
Count.java
package com.servlet; import java.io.I.*; import javax.servlet.*; import javax.servlet.http.*; public class Count extends HttpServlet { int count; public void init() throws ServletException { count=0; } public synchronized void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); 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|www.125jz.com</TITLE></HEAD>"); out.println(" <BODY>"); count++; out.print("你是第"+count+"个访问用户!"); out.println(" </BODY>"); out.println("</HTML>"); out.flush(); out.close(); } }
web.xml文件部署servlet:
<servlet> <servlet-name>Count</servlet-name> <servlet-class>com.servlet.Count</servlet-class> </servlet> <servlet-mapping> <servlet-name>Count</servlet-name> <url-pattern>/servlet/Count</url-pattern> </servlet-mapping>
125jz网原创文章。发布者:江山如画,转载请注明出处:http://www.125jz.com/2867.html