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

posted on 2014-11-12 16:35  欲上云端  阅读(970)  评论(0编辑  收藏  举报