概述:
通过servlet实例设置全局变量,记录多个servlet实例访问总次数。
HttpServletDemo02.java:
package com.fl.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HttpServletDemo02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletContext sc = getServletContext(); Integer click_num =(Integer) sc.getAttribute("clicknum"); if(click_num == null) sc.setAttribute("clicknum", 1); //在全局区域设置一个名为clicknum的属性,值为1。 else sc.setAttribute("clicknum", ++click_num); System.out.println(click_num); } @Override public void init(ServletConfig config) throws ServletException { ServletContext sc = config.getServletContext(); String temp = sc.getInitParameter("kkkk"); System.out.println(temp); } }
web.xml:
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>HttpServletDemo02</servlet-name> <servlet-class>com.fl.servlet.HttpServletDemo02</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>HttpServletDemo02</servlet-name> <url-pattern>/servlet/HttpServletDemo02</url-pattern> </servlet-mapping> </web-app>
结果:
思考一番后,感觉跟init方法有关,于是改了下:
public void init(ServletConfig config) throws ServletException { }
结果还是一样,于是又改了下:
public void init() throws ServletException {
}
终于正常了!