zoukankan      html  css  js  c++  java
  • ServletContext设置全局变量实现统计站点访问次数

    概述:

    通过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 {
        }
    终于正常了!
  • 相关阅读:
    winform combobox SelectedText值为空
    【转】C#、面向对象、设计模式学习
    oracle查询分区表中的数据
    ORA-14402:更新分区关键字列将导致分区更改
    winform列标题高度无法改变
    【转】c#中@的3种作用
    winform 弹出的form显示在最前端
    winform datagridview数据显示不全
    【转】如何把CD上的音乐拷贝到电脑上
    开关WIFI脚本
  • 原文地址:https://www.cnblogs.com/cq0143/p/10668322.html
Copyright © 2011-2022 走看看