码迷,mamicode.com
首页 > 其他好文 > 详细

ServletContext设置全局变量实现统计站点访问次数

时间:2019-04-08 09:13:48      阅读:111      评论:0      收藏:0      [点我收藏+]

标签:size   servlet   cli   text   get   str   etc   res   end   

概述:

通过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 {
    }
终于正常了!

 

ServletContext设置全局变量实现统计站点访问次数

标签:size   servlet   cli   text   get   str   etc   res   end   

原文地址:https://www.cnblogs.com/cq0143/p/10668322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!