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 use 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, only need change it’s init parameter value in web.xml.

How to get ServletConfig instance

You can use HttpServlet.getServletConfig() method to get it. HttpServlet inherit this method from GenericServlet.

servlet definition in web.xml

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.

Example for ServletConfig

Below java servlet example will get servlet name and all init parameters and print them in the page.

  1. 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);
    		}	
    	}

    servlet config example result page

ServletContext

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

Advantage of ServletContext

  1. Parameterized variable value in web.xml use <context-param> xml element.
  2. Can share common 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.

How to get ServletContext

We can use either GenericServlet.getServletContext() or ServletConfig.getServletContext() to get an instance of it.

ServletContext methods

web application context init parameter

  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 value.
  2. String getInitParameter(String paramName):
    Return the init parameter value by it’s name. In above web.xml picture, 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 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.

ServletContext Example

  1. This example will read all servlet context init parameter names and their values.

    Class: com.dev2qa.example.servletcontext.ReadSCInitParameters


    Access 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);
    		}
    	}
  2. This example will set a UserInfoDTO object in SetSCUserInfo servlet and get that object value in another servlet which is ReadSCUserInfo.

    Class: com.dev2qa.example.servletcontext.SetSCUserInfo


    Access 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());
    	}

    Class: com.dev2qa.example.servletcontext.ReadSCUserInfo


    Access 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.");
    		}
    	}

    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();
    	}
    }

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.

Download “ServletConfig-And-ServletContext-Example.zip” ServletConfig-And-ServletContext-Example.zip – Downloaded 62 times – 43 KB

(Visited 150 times, 1 visits today)
READ :   Deploy And Undeploy Java EE Web Applications In Tomcat

Leave a Reply

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.