aspose file tools*
The moose likes Servlets and the fly likes static variables and methods in servlet Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "static variables and methods in servlet" Watch "static variables and methods in servlet" New topic
Author

static variables and methods in servlet

hasan khan
Ranch Hand

Joined: Aug 04, 2003
Posts: 222

is there any harm in defining public static variables and methods in a Servlet and calling them from some other class or servlet or jsp files.
[ September 29, 2006: Message edited by: hasaN khaN ]

SCJP, SCWCD
Chetan Parekh
Ranch Hand

Joined: Sep 16, 2004
Posts: 3636
Servlets are also class � hence your can create static variables and methods in Servlets and access from other Servlets / Classes.

But the harm is that Servlet are not meant for that. They have defined role to be play in J2EE framework. Let your Servlets to do what it can do within the define boundary of role.

Defining static variables and method is crossing the boundary.


My blood is tested +ve for Java.
Ben Souther
Sheriff

Joined: Dec 11, 2004
Posts: 13410

First, static variables and static methods are two different topics.

Unless you have a real good reason to use them and you really know what you're doing, I'd avoid using static variables in web apps. Doing so can lead to some confusing behavior.
[ September 29, 2006: Message edited by: Ben Souther ]

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 60082
    
  65

Ben is correct in that read/write static variables aren't well-suited to the web app environment. Final static variables used to defiend constants are a different matter though, and should be used to define constant values rather than hard-coding literals throughout the code.


[Asking smart questions] [Bear's FrontMan] [About Bear] [Books by Bear]
Lucas Lee
Ranch Hand

Joined: Oct 02, 2006
Posts: 53
You must be careful of that class or instance variables in servlets for thread safe.
Container maybe send mutiple request to one servlet instance,so servlet (jsp also)is in multiple threads enviroment.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: static variables and methods in servlet
 
Similar Threads
Class and instance variables...
static mathods/variable inheritance
Static variables and performance....
Initializing an object at class level
Constructor and Initializer block