Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
692 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...