Different between ServleConfig and ServletContext

Many servlet’s developers are confuse about the different between “ServletConfig” and “ServletContext”. Actually the “ServletContext” name is quite confusing, it should change to “AppConfig” or “AppContext” in the future release 🙂

ContextConfig

1) This is one per “web application”, access globally by all the servlets’ class
2) web.xml – within the web-app element and outside the servlet element


    <web-app ...>
        <servlet>
		<servlet-name>ServletName</servlet-name>
		<servlet-class>com.mkyong.ServletDemo</servlet-class>
	</servlet>
	
	<context-param>
			<param-name>email</param-name>
			<param-value>[email protected]</param-value>
	</context-param>
   </web-app>

3) Servlet code


getServletContext().getInitParameter("email")

==> See the ServletContext example here

ServletConfig

1) This is one per “servlet”, only access for each specific servlet
2) web.xml – within the servlet element


    <web-app ...>
        <servlet>
		<servlet-name>ServletName</servlet-name>
		<servlet-class>com.mkyong.ServletDemo</servlet-class>

                 <init-param>
			<param-name>email</param-name>
			<param-value>[email protected]</param-value>
	         </init-param>

	</servlet>
   </web-app>

3) Servlet code


getServletConfig().getInitParameter("email")

==> See the ServletContext example here

5 comments on “Different between ServleConfig and ServletContext

  1. hi mkyong,

    please put example of connecting mongoDb with servlet
    with appConfig

    Reply
  2. Sir ur tutorial is very understable….
    I am really amazed of ur explaination…..I am also one of ur fan….

    Reply
  3. Nice and i am a fan of your Java tutorial.

    Noor Alam
    (SCJP,SCWCD,SCBCD)

    Reply
  4. Hi Thanks , it is really amazing tutorial ,

    but just one question what do u mean by

    one per “web application” & This is one per “servlet” ?

    I think so we can have multiple initial parameters per servlet and per web.xml

    Reply
    1. A web app can contains many servlets.

      one per “web application”, means it can access by “any” of the servlets within the application, globally.

      one per “servlet”, means it can only access for “a” specific servlet.

      Is this clear?

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *