Java学习者论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

手机号码,快捷登录

恭喜Java学习者论坛(https://www.javaxxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,购买链接:点击进入购买VIP会员
JAVA高级面试进阶视频教程Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程

Go语言视频零基础入门到精通

Java架构师3期(课件+源码)

Java开发全终端实战租房项目视频教程

SpringBoot2.X入门到高级使用教程

大数据培训第六期全套视频教程

深度学习(CNN RNN GAN)算法原理

Java亿级流量电商系统视频教程

互联网架构师视频教程

年薪50万Spark2.0从入门到精通

年薪50万!人工智能学习路线教程

年薪50万!大数据从入门到精通学习路线年薪50万!机器学习入门到精通视频教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程 MySQL入门到精通教程
查看: 363|回复: 0

[默认分类] Java Servlet(十一):一个servlet被10个浏览器客户端访问时会创建几个servlet实例?

[复制链接]
  • TA的每日心情
    开心
    2021-12-13 21:45
  • 签到天数: 15 天

    [LV.4]偶尔看看III

    发表于 2018-4-13 09:44:54 | 显示全部楼层 |阅读模式
    一般Servlet只初始化一次(只有一个实例)。对于更多的客户端请求,Server创建新的请求和响应对象,仍然激活此Servlet的service()方法,将这两个对象作为参数传递给该方法。如此重复以上的循环,但无需再调用init()方法。
    原因:
    出于性能的考虑:特别的对于门户网站而言,每一个Servlet在每一秒内的并发访问量都可以是成千上万的。在一个面向模块化开发的现在,常常一个点击操作就被定义为一个Servlet的实现,而如果Servlet的每一次被访问,都创建一个新的实例的话,服务器的可用资源消耗量将是一个相当重要的问题。
    退一步,一般Servlet的访问是很快的,每一个实例被快速的创建,又被快速的回收,GC的回收速度也跟不上,频繁的内存操作也将可能带来次生的问题。
    所以,Servlet的“单一实例化”是一个很重要的策略。
    此时为了更好理解servlet,这里附上servlet、httpservlet代码:
    Servlet源代码:

    1. package javax.servlet;  
    2. import java.io.IOException;  
    3. // Referenced classes of package javax.servlet:  
    4. // ServletException, ServletConfig, ServletRequest, ServletResponse  
    5. public interface Servlet  
    6. {  
    7.     public abstract void init(ServletConfig servletconfig)  
    8.         throws ServletException;  
    9.     public abstract ServletConfig getServletConfig();  
    10.     public abstract void service(ServletRequest servletrequest, ServletResponse servletresponse)  
    11.         throws ServletException, IOException;  
    12.     public abstract String getServletInfo();  
    13.     public abstract void destroy();  
    14. }  
    复制代码


    HttpServlet源代码:

    1. import java.io.IOException;  
    2. import java.io.Serializable;  
    3. import java.lang.reflect.Method;  
    4. import java.text.MessageFormat;  
    5. import java.util.Enumeration;  
    6. import java.util.ResourceBundle;  
    7. import javax.servlet.*;  
    8. // Referenced classes of package javax.servlet.http:  
    9. //            NoBodyResponse, HttpServletRequest, HttpServletResponse  
    10. public abstract class HttpServlet extends GenericServlet  
    11.     implements Serializable  
    12. {  
    13.     public HttpServlet()  
    14.     {  
    15.     }  
    16.     protected void doGet(HttpServletRequest req, HttpServletResponse resp)  
    17.         throws ServletException, IOException  
    18.     {  
    19.         String protocol = req.getProtocol();  
    20.         String msg = lStrings.getString("http.method_get_not_supported");  
    21.         if(protocol.endsWith("1.1"))  
    22.             resp.sendError(405, msg);  
    23.         else  
    24.             resp.sendError(400, msg);  
    25.     }  
    26.     protected long getLastModified(HttpServletRequest req)  
    27.     {  
    28.         return -1L;  
    29.     }  
    30.     protected void doHead(HttpServletRequest req, HttpServletResponse resp)  
    31.         throws ServletException, IOException  
    32.     {  
    33.         NoBodyResponse response = new NoBodyResponse(resp);  
    34.         doGet(req, response);  
    35.         response.setContentLength();  
    36.     }  
    37.     protected void doPost(HttpServletRequest req, HttpServletResponse resp)  
    38.         throws ServletException, IOException  
    39.     {  
    40.         String protocol = req.getProtocol();  
    41.         String msg = lStrings.getString("http.method_post_not_supported");  
    42.         if(protocol.endsWith("1.1"))  
    43.             resp.sendError(405, msg);  
    44.         else  
    45.             resp.sendError(400, msg);  
    46.     }  
    47.     protected void doPut(HttpServletRequest req, HttpServletResponse resp)  
    48.         throws ServletException, IOException  
    49.     {  
    50.         String protocol = req.getProtocol();  
    51.         String msg = lStrings.getString("http.method_put_not_supported");  
    52.         if(protocol.endsWith("1.1"))  
    53.             resp.sendError(405, msg);  
    54.         else  
    55.             resp.sendError(400, msg);  
    56.     }  
    57.     protected void doDelete(HttpServletRequest req, HttpServletResponse resp)  
    58.         throws ServletException, IOException  
    59.     {  
    60.         String protocol = req.getProtocol();  
    61.         String msg = lStrings.getString("http.method_delete_not_supported");  
    62.         if(protocol.endsWith("1.1"))  
    63.             resp.sendError(405, msg);  
    64.         else  
    65.             resp.sendError(400, msg);  
    66.     }  
    67.     private Method[] getAllDeclaredMethods(Class c)  
    68.     {  
    69.         if(c.equals(javax/servlet/http/HttpServlet))  
    70.             return null;  
    71.         Method parentMethods[] = getAllDeclaredMethods(c.getSuperclass());  
    72.         Method thisMethods[] = c.getDeclaredMethods();  
    73.         if(parentMethods != null && parentMethods.length > 0)  
    74.         {  
    75.             Method allMethods[] = new Method[parentMethods.length + thisMethods.length];  
    76.             System.arraycopy(parentMethods, 0, allMethods, 0, parentMethods.length);  
    77.             System.arraycopy(thisMethods, 0, allMethods, parentMethods.length, thisMethods.length);  
    78.             thisMethods = allMethods;  
    79.         }  
    80.         return thisMethods;  
    81.     }  
    82.     protected void doOptions(HttpServletRequest req, HttpServletResponse resp)  
    83.         throws ServletException, IOException  
    84.     {  
    85.         Method methods[] = getAllDeclaredMethods(getClass());  
    86.         boolean ALLOW_GET = false;  
    87.         boolean ALLOW_HEAD = false;  
    88.         boolean ALLOW_POST = false;  
    89.         boolean ALLOW_PUT = false;  
    90.         boolean ALLOW_DELETE = false;  
    91.         boolean ALLOW_TRACE = true;  
    92.         boolean ALLOW_OPTIONS = true;  
    93.         for(int i = 0; i < methods.length; i++)  
    94.         {  
    95.             Method m = methods[i];  
    96.             if(m.getName().equals("doGet"))  
    97.             {  
    98.                 ALLOW_GET = true;  
    99.                 ALLOW_HEAD = true;  
    100.             }  
    101.             if(m.getName().equals("doPost"))  
    102.                 ALLOW_POST = true;  
    103.             if(m.getName().equals("doPut"))  
    104.                 ALLOW_PUT = true;  
    105.             if(m.getName().equals("doDelete"))  
    106.                 ALLOW_DELETE = true;  
    107.         }  
    108.         String allow = null;  
    109.         if(ALLOW_GET && allow == null)  
    110.             allow = "GET";  
    111.         if(ALLOW_HEAD)  
    112.             if(allow == null)  
    113.                 allow = "HEAD";  
    114.             else  
    115.                 allow = (new StringBuilder()).append(allow).append(", HEAD").toString();  
    116.         if(ALLOW_POST)  
    117.             if(allow == null)  
    118.                 allow = "POST";  
    119.             else  
    120.                 allow = (new StringBuilder()).append(allow).append(", POST").toString();  
    121.         if(ALLOW_PUT)  
    122.             if(allow == null)  
    123.                 allow = "PUT";  
    124.             else  
    125.                 allow = (new StringBuilder()).append(allow).append(", PUT").toString();  
    126.         if(ALLOW_DELETE)  
    127.             if(allow == null)  
    128.                 allow = "DELETE";  
    129.             else  
    130.                 allow = (new StringBuilder()).append(allow).append(", DELETE").toString();  
    131.         if(ALLOW_TRACE)  
    132.             if(allow == null)  
    133.                 allow = "TRACE";  
    134.             else  
    135.                 allow = (new StringBuilder()).append(allow).append(", TRACE").toString();  
    136.         if(ALLOW_OPTIONS)  
    137.             if(allow == null)  
    138.                 allow = "OPTIONS";  
    139.             else  
    140.                 allow = (new StringBuilder()).append(allow).append(", OPTIONS").toString();  
    141.         resp.setHeader("Allow", allow);  
    142.     }  
    143.     protected void doTrace(HttpServletRequest req, HttpServletResponse resp)  
    144.         throws ServletException, IOException  
    145.     {  
    146.         String CRLF = "\r\n";  
    147.         String responseString = (new StringBuilder()).append("TRACE ").append(req.getRequestURI()).append(" ").append(req.getProtocol()).toString();  
    148.         for(Enumeration reqHeaderEnum = req.getHeaderNames(); reqHeaderEnum.hasMoreElements();)  
    149.         {  
    150.             String headerName = (String)reqHeaderEnum.nextElement();  
    151.             responseString = (new StringBuilder()).append(responseString).append(CRLF).append(headerName).append(": ").append(req.getHeader(headerName)).toString();  
    152.         }  
    153.         responseString = (new StringBuilder()).append(responseString).append(CRLF).toString();  
    154.         int responseLength = responseString.length();  
    155.         resp.setContentType("message/http");  
    156.         resp.setContentLength(responseLength);  
    157.         ServletOutputStream out = resp.getOutputStream();  
    158.         out.print(responseString);  
    159.         out.close();  
    160.     }  
    161.     protected void service(HttpServletRequest req, HttpServletResponse resp)  
    162.         throws ServletException, IOException  
    163.     {  
    164.         String method = req.getMethod();  
    165.         if(method.equals("GET"))  
    166.         {  
    167.             long lastModified = getLastModified(req);  
    168.             if(lastModified == -1L)  
    169.             {  
    170.                 doGet(req, resp);  
    171.             } else  
    172.             {  
    173.                 long ifModifiedSince = req.getDateHeader("If-Modified-Since");  
    174.                 if(ifModifiedSince < (lastModified / 1000L) * 1000L)  
    175.                 {  
    176.                     maybeSetLastModified(resp, lastModified);  
    177.                     doGet(req, resp);  
    178.                 } else  
    179.                 {  
    180.                     resp.setStatus(304);  
    181.                 }  
    182.             }  
    183.         } else  
    184.         if(method.equals("HEAD"))  
    185.         {  
    186.             long lastModified = getLastModified(req);  
    187.             maybeSetLastModified(resp, lastModified);  
    188.             doHead(req, resp);  
    189.         } else  
    190.         if(method.equals("POST"))  
    191.             doPost(req, resp);  
    192.         else  
    193.         if(method.equals("PUT"))  
    194.             doPut(req, resp);  
    195.         else  
    196.         if(method.equals("DELETE"))  
    197.             doDelete(req, resp);  
    198.         else  
    199.         if(method.equals("OPTIONS"))  
    200.             doOptions(req, resp);  
    201.         else  
    202.         if(method.equals("TRACE"))  
    203.         {  
    204.             doTrace(req, resp);  
    205.         } else  
    206.         {  
    207.             String errMsg = lStrings.getString("http.method_not_implemented");  
    208.             Object errArgs[] = new Object[1];  
    209.             errArgs[0] = method;  
    210.             errMsg = MessageFormat.format(errMsg, errArgs);  
    211.             resp.sendError(501, errMsg);  
    212.         }  
    213.     }  
    214.     private void maybeSetLastModified(HttpServletResponse resp, long lastModified)  
    215.     {  
    216.         if(resp.containsHeader("Last-Modified"))  
    217.             return;  
    218.         if(lastModified >= 0L)  
    219.             resp.setDateHeader("Last-Modified", lastModified);  
    220.     }  
    221.     public void service(ServletRequest req, ServletResponse res)  
    222.         throws ServletException, IOException  
    223.     {  
    224.         HttpServletRequest request;  
    225.         HttpServletResponse response;  
    226.         try  
    227.         {  
    228.             request = (HttpServletRequest)req;  
    229.             response = (HttpServletResponse)res;  
    230.         }  
    231.         catch(ClassCastException e)  
    232.         {  
    233.             throw new ServletException("non-HTTP request or response");  
    234.         }  
    235.         service(request, response);  
    236.     }  
    237.     private static final String METHOD_DELETE = "DELETE";  
    238.     private static final String METHOD_HEAD = "HEAD";  
    239.     private static final String METHOD_GET = "GET";  
    240.     private static final String METHOD_OPTIONS = "OPTIONS";  
    241.     private static final String METHOD_POST = "POST";  
    242.     private static final String METHOD_PUT = "PUT";  
    243.     private static final String METHOD_TRACE = "TRACE";  
    244.     private static final String HEADER_IFMODSINCE = "If-Modified-Since";  
    245.     private static final String HEADER_LASTMOD = "Last-Modified";  
    246.     private static final String LSTRING_FILE = "javax.servlet.http.LocalStrings";  
    247.     private static ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");  
    248. }  
    复制代码

    1. 参考:《[url=https://zhidao.baidu.com/question/500404314.html].init()方法成功完成后,Servlet可以接受请求.默认有多少个Servlet实例被创建[/url]》、《[url=http://www.cnblogs.com/yy3b2007com/p/5224362.html]Java Servlet(二):servlet配置及生命周期相关(jdk7+tomcat7+eclipse)[/url]》
    复制代码
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|Java学习者论坛 ( 声明:本站资料整理自互联网,用于Java学习者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-4-26 21:32 , Processed in 0.370279 second(s), 46 queries .

    Powered by Discuz! X3.4

    © 2001-2017 Comsenz Inc.

    快速回复 返回顶部 返回列表