Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
694 views
in Technique[技术] by (71.8m points)

servlets - Value passed with request.setAttribute() is not available by request.getParameter()

I give a string variable a value in the normal execution of the code ,but if an exception happen I will give it another value , the problem is that in catch block the value is still the same as i assign first .

Here is my code ,first I assign page value "addUser" inside try block and in catch I give it "ErrorPage" value , I send the value of page within http request to forword method and inside it i print the value of page. I cause an error in the excution of the code an i want it to go through catch block , and it does , but when it send the page value to the forword function the value of page is "addUser" not "ErrorPage" although i assign it to "ErrorPage" !!

String page = "addUser";

try {
    // ...

    request.setAttribute("page", page);
    forward(request, response);
} catch (SQLException e) {
    page = "ErrorPage";
    request.setAttribute("page", page);
    forward(request, response);
}

and here is the forword function

String page = request.getParameter("page");
System.out.println("page is " + page); // each time it prints addUSer

Can someone help? and thanx in advance.

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're calling request.getParameter() instead of request.getAttribute() to obtain the value. Since you've set it as request attribute, you should also get it as request attribute.

So:

request.setAttribute("foo", foo);

is only available by

Object foo = request.getAttribute("foo"); // NOT getParameter().

The getParameter() is only for HTTP request parameters as you can specify in request URL or in input fields of HTML forms.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...