Scope of variable in servlet in java

Satyapriyanayak
Posted by Satyapriyanayak under Others category on | Points: 40 | Views : 676
Servlet 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.

Ex:-
user.java
//creating page variable
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class user extends HttpServlet
{
int x=0;
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter out=res.getWriter();
out.println("<Html>");
out.println("<Body bgcolor='CYAN'>");
out.println("<H1>"+x+"</h1>");
x++;
out.println("</Body>");
out.println("</Html>");
}
}

web.xml settings

<?xml version="1.0" encoding="ISO-8859-1"?>


<servlet>
<servlet-name>user</servlet-name>
<servlet-class>user</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>user</servlet-name>
<url-pattern>/user</url-pattern>
</servlet-mapping>

</web-app>

Compilation
javac -cp servlet-api.jar user.java (for tomcat 6.0)

Comments or Responses

Login to post response