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就是这个线程所特有的...

  • 相关阅读:
    ASP.NET : 自定义HttpModule的时候要注意的问题
    ASP.NET : Win7 及 IIS 7中对于处理程序映射
    .NET : 一定不要忘记关闭DataReader对象
    IE 8 Accelerator加速器开发介绍{转载}
    .NET : CLR Profiler的使用
    .NET : 在实现WCF的双工服务时可能遇到的问题
    Silverlight学习资源
    .NET : 如何查看值类型的大小
    .NET: 如何通过AppDomain动态加载插件程序
    Web.config中的特殊字符
  • 原文地址:https://www.cnblogs.com/Wen-yu-jing/p/4092631.html
Copyright © 2011-2022 走看看