Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static variables and methods in servlet

 
hasan khan
Ranch Hand
Posts: 223
Eclipse IDE Firefox Browser Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Chetan Parekh
Ranch Hand
Posts: 3640
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ben Souther
Sheriff
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Bear Bibeault
Author and ninkuma
Marshal
Pie
Posts: 64683
86
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Lucas Lee
Ranch Hand
Posts: 53
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic