• Post Reply Bookmark Topic Watch Topic
  • New Topic

How to make jsp with instance variable thread safe?

 
RabiDas Sharma
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
why instance variables in jsp isn't good practice?

My book says value of instance variables in jsp may be
read and updated at the same time by multiple threads
so jsp won't be thread safe anymore if we use instance
variables.........
can anyone give one example???

Is there no other way to make jsp with instance variables Thread safe???
If yes how???

thanks in advance
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65524
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It is 2014, not 2001. There should be no Java code in a JSP at all. None. No instance variables, no Java code.

You should be using the JSTL and EL and not writing JSP like it was written over 12 years ago.

If this is a legacy application from that time, then do not introduce instance variables. They will cause problems.
 
Heena Agarwal
Ranch Hand
Posts: 262
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Also we shouldn't forget that JSPs are translated into servlets and the container creates only one instance of the servlets. Every time we send a new request, a new thread is created.
 
Bear Bibeault
Author and ninkuma
Marshal
Posts: 65524
105
IntelliJ IDE Java jQuery Mac Mac OS X
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which is exactly what causes the thread-safety issue. Any values stored in instance variables will be overwritten by other requests.

There are many good reasons that putting Java scriptlets in a JSP is obsolete. This is just one of them.

Bottom line: write JSPs correctly and there are few opportunities for threading issues.
 
RabiDas Sharma
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi everyone,
Suppose i want to count the no. Of requests made to a jsp page then how can i do that if i'm not supposed to use instance variables in jsp page
 
Ulf Dittmer
Rancher
Posts: 42970
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Put that code into the controller that handles access to the JSP (assuming there is one, which, of course, there should be - MVC has been standard practice for a very, very long time by now).

If there isn't, filters would be an option.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!