• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Just to share

 
Poonam Agarwal
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Consider the code for a jsp page :

hey ranchers,

just to share this info. because sometime we look at the code in very obvious way AND forget out the basic concepts. Atleast I did, when I attempt this question

Assuming that the servlet context of the web application DOES NOT have any attribute by the name of "key", what will the above jsp page print when requested?

1. It will not compile because the getAttribute() returns an Object which must be cast to String before assigning to thevalue.
2. It will print "null".
3. It will throw a NullPointerException.
4. It will print "" (empty string).
5. None of these.

the 5th one is correct. I choose the 2 one which is not.

Explaination

The point in option 1 is correct. However, even before the casting problem, the given JSP page will not compile because 'application' implicit variable (or any implicit variables for that matter) are only accessible in the service method. They are not accessible in the init() method. To access servlet context in the jspInit() method, you should call: this.getServletConfig().getServletContext().

Thanks
 
Ankit Garg
Sheriff
Posts: 9577
33
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hey this question also got me. I chose option 1
 
Poonam Agarwal
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It 's TRICKY
 
Milton Ochoa
Ranch Hand
Posts: 336
Firefox Browser Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thank you for the share
 
Chithra Salam
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why we need to access ServletContext thr servlet config( this.getServletConfig().getServletContext(). ).I think in jspInit we can call this.getServletContext() , no need to access thr config.

Please correct me if I am wrong.
 
ankit kumar
Ranch Hand
Posts: 108
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Chithra Salam wrote:Why we need to access ServletContext thr servlet config( this.getServletConfig().getServletContext(). ).I think in jspInit we can call this.getServletContext() , no need to access thr config.




ya you are right this holds the current servlet config refrence..
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic