What is a servletcontext

本文详细介绍了ServletContext的概念及其在Web应用中的作用。解释了如何通过web.xml配置初始化参数,并在多个Servlet及JSP页面间共享这些参数。此外,还对比了ServletContext与ServletConfig的区别,并介绍了ServletContextListener的应用场景。

What is a servletcontext

ServletContext is a configuration Object which is created when web application is started. It contains different initialization parameter that can be configured in web.xml.

Example of ServletContext with scenario

You are developing a web application where you want to access the email of administrator in whole application. You want to set this email id @ one location and every Servlet and Jsp can access that email. In that case you will take the help of ServletContext. You can add this email in servletcontext via init parameter in web.xml. Now this value (Email id of administrator) will be available to every Jsp and Servlet in the web application.

Life Cycle of ServletContext

Step 1: Servlet container reads the DD (Deployment Descriptor – web.xml) and creates the name/value string pair for each <context-param> when web application is getting started.

Step 2: Container creates the new Instance of ServletContext.

Note*: ServletContext is an Interface.

Step 3: Servlet container gives the ServletContext a reference to each name/value pair of the context init parameter.

Step 4: Every servlet and JSP in the same web application will now has access to this ServletContext.

Servlet context init parameter Syntax

 

 

Difference from ServletConfig

  • ServletConfig is one per servlet while ServletContext is one per web application.
  • ServletContext is available to all servlet & jsp in web application while ServletConfig will be available only specific servlet.
  • Difference in the syntax for servletcontext and servletconfig.

What is servletcontextlistener

Now you know that you can set init parameter in ServletContext & this Servletcontext will be initialized when application starts. After initialization this servletcontext will be available to all servlet and jsp. But what if you want to perform some kind of action when context initialization/destruction process happens. This is the situation when you will take the help of servletcontextlistener.

 

Bullet Points

  • Only one ServletContext is available per web application.
  • Every servlet in the same web application will have access to servletcontext.
  • It is used to access application level parameter.
  • If application is in distributed environment then there will be one servletcontext per JVM.
  • ServletContext has init parameter that can be configured in web.xml.

转载于:https://www.cnblogs.com/hephec/p/4556594.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值