That is so wrong. In the second line the req object is null. In the third the session would be undefined (or null if you choose to say) as the second line throws exception.
Execution does not reach line 3.

Farakh, if the code snippet is part of a servlet, then the servlet will have an initialized HttoServletRequest object.
Guess where it is ?

The main problem is "this is not a part of servlet and am trying to write a mehod to get session and return it". Usually we are initializing in the way e.g. Connection con = null;

My english is not so good and I think I am unable to describe well my question. Basically I intend to know why I can not initialize HttpServletRequest like Connection con = null; or String str = "" or int i = 0;

I just wanted to show him, that the session object is null. I too know that, the 3rd line won't execute. Anyways thanks for the correction.

Farakh khan,

HttpServletRequest, as the name implies, is an object used in Http Servlet. You cannot use it outside a Servlet or jsp (as far as I know). I would like to know whether you are developing a web application or stand alone application? Because you seemed to be confused (only to me).

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
--- Martin Fowler

Farakh khan

Ranch Hand

Posts: 833

posted 2 years ago

Thanks again for your favorable replies

I am developing web based application. I am trying to make method outside servlet. In my mind there was other examples like:

OK. If you want your methods outside servlet its fine. But if you want to handle request and response objects outside a servlet, you should pass it to the class or method where you are performing the operations. Say

and then you have to return the same request object to the servlet but this is not a recommended method. Servlets are used for handling request and response objects, so you have to perform all operations, with regards to them, in the servlets. And again if you want to pass the request object, it should have been created in your servlet.

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand."
--- Martin Fowler