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

半世苍凉 提交于 2019-12-17 03:43:08

问题


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.


回答1:


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.




回答2:


In addition to BalusC's point"

In your code you have declared two "String page" variable. This will not compile. I think the parameter that you are passing to the request in the catch must be the "other" page variable. But it is hard to tell since this is not a true example.



来源:https://stackoverflow.com/questions/4348676/value-passed-with-request-setattribute-is-not-available-by-request-getparamete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!