Willam has answered about the HttpServletRequest object.
Farakh khan wrote: even say its hard coded null then why it not reading
Look from where you are getting the String langPref.
Just think about how do you initialize a servlet and what are all the basic things you will do after initializing the servlet
Partheban Udayakumar wrote:
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.
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).
So you are developing a web application. OK.
Farakh khan wrote: I am trying to make method outside servlet
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.
Partheban Udayakumar wrote:and then you have to return the same request object to the servlet but this is not a recommended method.
Indeed not a recommended way of doing it. Instead extract the data from the request/session objects and pass it to your method.
Partheban Udayakumar wrote: And again if you want to pass the request object, it should have been created in your servlet.
For the record, request object is not "created" inside the servlet, it is created inside the servlet container and passed to the servlet.