store a HttpServletRequst in a HttpSession

Go To StackoverFlow.com

0

I want to store a HttpServletRequestobject in a HttpSession as an attribute.

     protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {       
request.getSession().setAttribute("ses",request);  

Here is how I get it back in another servlet,

HttpSession ses=r.getSession(false);
HttpServletRequest rq=(HttpServletRequest)ses.getAttribute("ses");  

Here rq is not nul when I check it in a if statement. My problem is, when I try to get a parameter which is in the request object, a null-point exception is thrown. How can I store a request as I can get parameters back again?

2012-04-04 16:47
by Débora
you can set the parameters in session and get back right. - Ramesh Kotha 2012-04-04 16:48
parameters ?? or attributes ?I think, attributes. Here also I have showed setting attributes - Débora 2012-04-04 16:52
i mean why you are setting request object in session, it contains lot of information which you dont need, set the attributes what you need in session and get them - Ramesh Kotha 2012-04-04 16:56
at one point of my app, the client sends some information(lots of details) which are useful again in a later time in a request. the easiest way which I thought was is to store that request in a session - Débora 2012-04-04 17:06
You shouldn't do this. Extract the useful information into a custom serializable object, and store this object in the session - JB Nizet 2012-04-04 17:10
ok, Thank you. I also feel that lots of unnecessary information load into the session.Better to extract useful info into a object and put it into session as u mentioned - Débora 2012-04-04 17:25


4

This is not possible and it makes technically also no sense. The HTTP servlet request instance is expired/garbaged when the associated HTTP servlet response is committed and finished. The HTTP servlet request instance is therefore not valid anymore in a different request. Invoking any methods on it will throw exceptions in all colors because the stored instance does not point to anything anymore. The initial HTTP servlet request has already finished doing its job is already been expired/garbaged.

You need to extract exactly the information you need from the request and store that information in the session instead of trying to access it in a different request. E.g.

String foo = request.getParameter("foo");
request.getSession().setAttribute("foo", foo);

and then

String foo = (String) request.getSession().getAttribute("foo");

See also:

2012-04-04 18:07
by BalusC
Ads