ServletConfig Vs ServletContext

ServletConfig is used to read servlet configuration data in web.xml. Web container will create one ServletConfig instance for each servlet. The advantage of using this object is that you can make your servlet variable’s value parameterized. You can save the variable value in web.xml as servlet init parameters and get that value from web.xml in your java code when you need them. This way you do not need to change servlet java code often, you only need to change the init parameter value in web.xml.

1. How to get ServletConfig instance.

  1. You can use HttpServlet.getServletConfig() method to get it. HttpServlet inherit this method from GenericServlet.
    <servlet>
        <description></description>
        <display-name>ServletConfigExample</display-name>
        <servlet-name>ServletConfigExample</servlet-name>
        <servlet-class>com.dev2qa.example.servletconfig.ServletConfigExample</servlet-class>
        <init-param>
          <description></description>
          <param-name>userName</param-name>
          <param-value>dev2qa.com</param-value>
        </init-param>
        <init-param>
          <description></description>
          <param-name>password</param-name>
          <param-value>dev2qa.com</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>ServletConfigExample</servlet-name>
        <url-pattern>/ServletConfigExample</url-pattern>
    </servlet-mapping>

2. ServletConfig methods.

  1. String getServletName(): Get servlet name defined in web.xml, in above picture, the servlet name is ServletConfigExample.
  2. String getInitParameter(String paramName): Get init parameter value, the parameter name is paramName. In above picture if paramName is password, then getInitParameter(“password”) return dev2qa.com.
  3. Enumeration getInitParameterNames(): This method return all the init parameter names in an Enumeration object, you need to iterate it to get all init parameter name and use getInitParameter(String paramName) to get related value.
  4. ServletContext getServletContext(): Return an instance of ServletContext, this is used to get and set configuration data in web application scope. We will introduce it later.

3. Example for ServletConfig.

  1. Below java servlet example will get the servlet name and all init parameters and print them on the page.
  2. Class: com.dev2qa.example.servletconfig.ServletConfigExample,
    Access Url: http://localhost:8080/Dev2qaWebAppExample/ServletConfigExample

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		
    	PrintWriter pw = resp.getWriter();
    	/* Get ServletConfig object. */
    	ServletConfig sc = this.getServletConfig();
    	
    	/* Get servlet name. */
    	String servletName = sc.getServletName();
    	pw.println("Servlet Name : " + servletName);
    	/* Get all init parameter names.*/
    	Enumeration<String> enu = sc.getInitParameterNames();
    	/* Iterate parameter name and get related value.*/
    	while(enu.hasMoreElements())
    	{
    		String paramName = enu.nextElement();
    		String paramValue = sc.getInitParameter(paramName);
    		pw.println(paramName + " = " + paramValue);
    	}	
    }
  3. Below is the above source code execution result.
    servlet-config-example-result-page

4. ServletContext.

  1. ServletContext instance is created by a web container when you deploy a web application in it.
  2. One web application has only one ServletContext object.

4.1 Advantage of ServletContext.

  1. Parameterized variable value in web.xml use <context-param> xml element.
  2. Can share commonly used values between servlets.
  3. Do not need to change servlet java code often, only need to change xml.
  4. Transfer object in web application use setAttribute() and getAttribute() method.

4.2 How to get ServletContext.

  1. We can use either GenericServlet.getServletContext() or ServletConfig.getServletContext() to get an instance of it.
    <context-param>
       <param-name>applicationUserName</param-name>
       <param-value>dev2qa.com</param-value>
    </context-param>
    <context-param>
       <param-name>applicationPassword</param-name>
       <param-value>dev2qa.com</param-value>
    </context-param>

4.3 ServletContext methods.

  1. Enumeration getInitParameterNames(): Used to get all application scope init parameter names in an Enumeration object. You need to iterate it and use getInitParameter(String paramName) to get related init parameter values.
  2. String getInitParameter(String paramName): Return the init parameter value by it’s name. In the above web.xml snippet, if the paramName is applicationUserName then the method will return dev2qa.com.
  3. void setAttribute(String attrName,Object objectValue): Set the objectValue in application scope. The object name is the value of the attrName input parameter.
  4. Object getAttribute(String attrName): Get the object in application scope which name is input parameter attrName’s value.
  5. void removeAttribute(String attrName): Remove the object in servlet context which name is input parameter attrName’s value.

4.4 ServletContext Example.

  1. This example will read all servlet context init parameter names and their values.
  2. Class: com.dev2qa.example.servletcontext.ReadSCInitParametersAccess url: http://localhost:8080/Dev2qaWebAppExample/ReadSCInitParameters
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		PrintWriter pw = resp.getWriter();
    		
    		/* Get ServletContext object.*/
    		ServletContext sc = this.getServletContext();
    		
    		/* Get all application init parameter names. */
    		Enumeration<String> enu = sc.getInitParameterNames();
    		while(enu.hasMoreElements())
    		{
    			String paramName = enu.nextElement();
    			String paramValue = sc.getInitParameter(paramName);
    			
    			pw.println(paramName + " = " + paramValue);
    		}
    	}
  3. This example will set a UserInfoDTO object in SetSCUserInfo servlet and get that object value in another servlet which is ReadSCUserInfo.
  4. Class: com.dev2qa.example.servletcontext.SetSCUserInfoAccess Url: http://localhost:8080/Dev2qaWebAppExample/SetSCUserInfo
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		
    		/* Create an object to store user info.  */
    		UserInfoDTO uiDto = new UserInfoDTO();
    		
    		uiDto.setUserName("Jerry Zhao");
    		uiDto.setPassword("dev2qa.com");
    		uiDto.setUerIsFemale(false);
    		uiDto.setUserAge(100);
    		uiDto.setUserEmail("[email protected]");
    		
    		/* Get ServletContext object. */
    		ServletContext sc = this.getServletContext();
    		
    		/* Set UserInfoDto in ServletContext object which is application scope. */
    		sc.setAttribute("userInfoDto", uiDto);
    		
    		/* Get the object from servlet context in same servlet*/
    		UserInfoDTO userInfoDto1 = (UserInfoDTO)sc.getAttribute("userInfoDto");
    		
    		/* Print user info to web page.*/
    		PrintWriter pw = resp.getWriter();
    		pw.println("Below user info is read from servlet context stored UserInfoDTO object.");
    		pw.println(userInfoDto1.toString());
    	}
  5. Class: com.dev2qa.example.servletcontext.ReadSCUserInfoAccess Url: http://localhost:8080/Dev2qaWebAppExample/ReadSCUserInfo
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		/* Get ServletContext object. */
    		ServletContext sc = this.getServletContext();
    		
    		PrintWriter pw = response.getWriter();
    		
    		/* Get the object from servlet context in another servlet*/
    		Object userInfoDtoObj = sc.getAttribute("userInfoDto");
    		
    		if(userInfoDtoObj!=null)
    		{
    			UserInfoDTO userInfoDto1 = (UserInfoDTO)userInfoDtoObj;
    			
    			/* Print user info to web page.*/
    			pw.println("Below user info is stored in SetSCUserInfo servlet.");
    			pw.println(userInfoDto1.toString());
    		}else
    		{
    			pw.println("Can not read UserInfoDTO object from servlet context.");
    		}
    	}=
  6. Class : com.dev2qa.example.dto.UserInfoDTO
    /* This class is used to store user info.*/
    public class UserInfoDTO {
    
    	private String userName = "";
    	
    	private String password = "";
    	
    	private int userAge = 0;
    	
    	private String userEmail = "";
    	
    	private boolean uerIsFemale = true;
    
    	public String getUserName() {
    		return userName;
    	}
    
    	public void setUserName(String userName) {
    		this.userName = userName;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public int getUserAge() {
    		return userAge;
    	}
    
    	public void setUserAge(int userAge) {
    		this.userAge = userAge;
    	}
    
    	public String getUserEmail() {
    		return userEmail;
    	}
    
    	public void setUserEmail(String userEmail) {
    		this.userEmail = userEmail;
    	}
    
    	public boolean isUerIsFemale() {
    		return uerIsFemale;
    	}
    
    	public void setUerIsFemale(boolean uerIsFemale) {
    		this.uerIsFemale = uerIsFemale;
    	}
    
    	@Override
    	public String toString() {
    		StringBuffer retBuf = new StringBuffer();
    		
    		retBuf.append("User Name : " + this.getUserName());
    		retBuf.append(" , Password : " + this.getPassword());
    		retBuf.append(" , User Email : " + this.getUserEmail());
    		retBuf.append(" , User Age : " + this.getUserAge());
    		retBuf.append(" , User is Female : " + this.isUerIsFemale());
    		
    		return retBuf.toString();
    	}
    }

5. Difference between ServletConfig and ServletContext.

  1. ServletConfig is used to get configuration for a single servlet.
  2. ServletContext is used to set and get configuration for the whole web application.
  3. ServletContext has setAttribute(), getAttribute() and removeAttribute() method, these methods can be used to share or remove object between servlet in whole web application.

Subscribe to receive more programming tricks.

We don’t spam!

Subscribe to receive more programming tricks.

We don’t spam!

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.