Scope of Variable in Servlet

Servlets can use four types of scope for the variables
  1. Local scope
  2. Page scope
  3. Session scope
  4. Application or server scope.

Local scope

 
If a variable gets declared inside any method of the servlet or any block then it becomes local scope.
 

Page scope

 
If a variable can be available to all parts of the servlets and all users share one instance of the variable, then it becomes page scope. An instance or class variable of the servlet can be called as page scope variable. Such types of variables can be used to share common information about all users in all servlets.
 
Example
 
user.java
  1. //creating page variable  
  2. import javax.servlet.*;  
  3. import java.io.*;  
  4. import javax.servlet.http.*;  
  5. public class user extends HttpServlet {  
  6.     int x = 0;  
  7.     public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {  
  8.         PrintWriter out = res.getWriter();  
  9.         out.println("<Html>");  
  10.         out.println("<Body bgcolor='CYAN'>");  
  11.         out.println("<H1>" + x + "</h1>");  
  12.         x++;  
  13.         out.println("</Body>");  
  14.         out.println("</Html>");  
  15.     }  
  16. }  
Web.xml settings
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!--  
  3. Licensed to the Apache Software Foundation (ASF) under one or more  
  4. contributor license agreements. See the NOTICE file distributed with  
  5. this work for additional information regarding copyright ownership.  
  6. The ASF licenses this file to You under the Apache License, Version 2.0  
  7. (the "License"); you may not use this file except in compliance with  
  8. the License. You may obtain a copy of the License at  
  9. http://www.apache.org/licenses/LICENSE-2.0  
  10. Unless required by applicable law or agreed to in writing, software  
  11. distributed under the License is distributed on an "AS IS" BASIS,  
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13. See the License for the specific language governing permissions and  
  14. limitations under the License.  
  15. -->  
  16. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  17. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  18. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  19. version="2.5">  
  20.   
  21. <servlet>  
  22. <servlet-name>user</servlet-name>  
  23. <servlet-class>user</servlet-class>  
  24. </servlet>  
  25.   
  26. <servlet-mapping>  
  27. <servlet-name>user</servlet-name>  
  28. <url-pattern>/user</url-pattern>  
  29. </servlet-mapping>  
  30.   
  31. </web-app>  
Compilation
 
javac -cp servlet-api.jar user.java (for tomcat 6.0)
 
Servlet1.gif 
 
Output
 
Run the tomcat then write the below line in the URL
 
http://localhost:8081/serv/user
 
Here serv is the Context path, which we mentioned in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.
 
Servlet2.gif 
 
Note: - When we refresh the page the number goes on increasing. Also when we open a new browser and write the above URL then also number goes on increasing. So, here we note that for every visit of new user the number goes on increasing until the server gets restarted.
 

Session scope

 
If a variable can be available to all servlets and for each user it becomes individual then it is called as user or session scope. Such types of variable can be used to store individual information for each user and for multiple servlets. It can be created by using cookie or session.
 

Application or server scope

 
If a variable can be available to all servlets and all users share a common instance of the variable then it is called as application or server scope. Such type of variables can be used to store common information about all servlet and all users.
 
Creation and reading process of application scope variables
  1. Create the object of javax.servlet.servletContext by using getServletContext() method of generic servlet.The object of servlet context represent all the servlets present in the servlet container.
  2. Use setAttribute() of servlet context to create application scope variable. It accepts two parameters as the name of the variable and value of the variable.
  3. Use getAttribute() of servlet context to find value of application scope variable. If the specified variable does not exits then it returns null.
Example
 
welcome.java
  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4. public class welcome extends HttpServlet {  
  5.     public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {  
  6.   
  7.         ServletContext sc = getServletContext();  
  8.         Integer x = (Integer) sc.getAttribute("hit");  
  9.         PrintWriter out = res.getWriter();  
  10.         out.println("<html><body>");  
  11.         if (x == null)  
  12.             x = 1;  
  13.         else  
  14.             x++;  
  15.         sc.setAttribute("hit", x);  
  16.         out.println("<h1>Welcome </h1>");  
  17.         out.println("<h3><a href='./user1'>Hit count</a></h3>");  
  18.         out.println("</body></html>");  
  19.     }  
  20. }  
user1.java
  1. import java.io.*;  
  2. import javax.servlet.*;  
  3. import javax.servlet.http.*;  
  4. public class user1 extends HttpServlet {  
  5.     public void doGet(HttpServletRequest req, HttpServletResponse res)  
  6.     throws ServletException, IOException {  
  7.         ServletContext sc = getServletContext();  
  8.         Integer x = (Integer) sc.getAttribute("hit");  
  9.         PrintWriter out = res.getWriter();  
  10.         out.println("<html><body>");  
  11.         out.println("<H1>Users visited " + x + "</h1>");  
  12.         out.println("</body></html>");  
  13.     }  
  14. }  
Web.xml settings
  1. <?xml version="1.0" encoding="ISO-8859-1"?>  
  2. <!--  
  3. Licensed to the Apache Software Foundation (ASF) under one or more  
  4. contributor license agreements. See the NOTICE file distributed with  
  5. this work for additional information regarding copyright ownership.  
  6. The ASF licenses this file to You under the Apache License, Version 2.0  
  7. (the "License"); you may not use this file except in compliance with  
  8. the License. You may obtain a copy of the License at  
  9. http://www.apache.org/licenses/LICENSE-2.0  
  10. Unless required by applicable law or agreed to in writing, software  
  11. distributed under the License is distributed on an "AS IS" BASIS,  
  12. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  
  13. See the License for the specific language governing permissions and  
  14. limitations under the License.  
  15. -->  
  16. <web-app xmlns="http://java.sun.com/xml/ns/javaee"  
  17. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  18. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  
  19. version="2.5">  
  20.   
  21. <servlet>  
  22. <servlet-name>welcome</servlet-name>  
  23. <servlet-class>welcome</servlet-class>  
  24. </servlet>  
  25.   
  26. <servlet>  
  27. <servlet-name>user1</servlet-name>  
  28. <servlet-class>user1</servlet-class>  
  29. </servlet>  
  30.   
  31. <servlet-mapping>  
  32. <servlet-name>welcome</servlet-name>  
  33. <url-pattern>/welcome</url-pattern>  
  34. </servlet-mapping>  
  35.   
  36. <servlet-mapping>  
  37. <servlet-name>user1</servlet-name>  
  38. <url-pattern>/user1</url-pattern>  
  39. </servlet-mapping>  
  40.   
  41. </web-app>  
Compilation
 
javac -cp servlet-api.jar welcome.java (for tomcat 6.0)
javac -cp servlet-api.jar user1.java (for tomcat 6.0)
 
Servlet3.gif 
 
Output
 
Run the tomcat then write the below line in the URL
 
Here serv is the Context path, which we mentioned in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.
 
http://localhost:8081/serv/welcome
 
Servlet4.gif 
 
Note: - In welcome. Java file the value is stored in hit variable and it is retrieved in user1.java file. So, here we note that for every visit of new user the number goes on increasing until the server gets restarted.
 

Conclusion

In this article, we learned about Scope of variables in Java Servlets, various types of scopes and their java implementation


Similar Articles