zoukankan      html  css  js  c++  java
  • Servlet单例模式(注意)

     1 package com.servlet;
     2 
     3 import java.io.IOException;
     4 
     5 import javax.servlet.ServletException;
     6 import javax.servlet.http.HttpServlet;
     7 import javax.servlet.http.HttpServletRequest;
     8 import javax.servlet.http.HttpServletResponse;
     9 
    10 /**
    11  * Servlet implementation class Test
    12  */
    13 public class Test extends HttpServlet {
    14     private static final long serialVersionUID = 1L;
    15     private long abc = 123;
    16     ThreadLocal<String> local = new ThreadLocal<String>();
    17     /**
    18      * @see HttpServlet#HttpServlet()
    19      */
    20     public Test() {
    21         super();
    22         // TODO Auto-generated constructor stub
    23     }
    24 
    25     /**
    26      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    27      */
    28     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    29         // TODO Auto-generated method stub
    30         System.out.println(abc);
    31         abc = 134;
    32         
    33     }
    34 
    35     /**
    36      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    37      */
    38     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    39         // TODO Auto-generated method stub
    40     }
    41 
    42 }

    servlet是单例模式 其内部定义的变量是所有用户共享的(多线程共享) 当一个用户改变了这个变量的值,其他用户访问得到的是改变之后的值
    servlet中的变量最好放在map中 线程安全的map ConcurrentHashMap(),以sessionid为主键存放,这样每个用户(线程)都会有单独属于自己的一个值
    不会受到其他用户的影响,

    使用ThreadLocal时 每次访问servlet 都是一个新的线程,ThreadLocal就是这个线程所特有的...

  • 相关阅读:
    Python模块进阶、标准库、扩展库
    python垃圾回收机制
    VMWare workstation 安装 CentOS 8后自适应调整分辨率(如1920x1080)
    使用 Zeal 打造属于自己的文档
    Erlang 开发者的福音:IntelliJ IDEA 的 Erlang 插件
    Intellij IDEA 14的注册码
    在Intellij IDEA或者PhpStorm下用X-debug调试PHP
    PHPCMS 核心代码与 www 分离部署
    PHPCMS如何实现后台访问限制?
    推荐:PHPCMS v9 安全防范教程!
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4092631.html
Copyright © 2011-2022 走看看