My jsp page has a form that sends a POST request to the servlet, which checks a few things from the form input, based on the result of this check ads an attribute to the request, and then redirects the request to the same jsp, which should show an alert message accordingly. This is my servlet:
req.setAttribute("error", "message");
req.getRequestDispatcher("/htmls/myjsp.jsp").forward(req, resp);
And then myjsp.jsp has:
<script type="text/javascript">
var msg ='<%request.getAttribute("error"); %>';
if (msg != null && msg != "") {
function alertName(){
alert(msg);
}
}
</script>
And at the botton of the jsp:
<script type="text/javascript"> window.onload = alertName; </script>
This doesn't work, msg is always an empty string. The string is correctly added as an attribute, but I guess the script in the jsp to retrieve that attribute is not correct. In the developer tools, I see that the resultant html is:
<script type="text/javascript">
var msg ='';
if (msg != null && msg != "") {
function alertName(){
alert(msg);
}
}
</script>
This solution is based on the accepted answer here.
CodePudding user response:
I fixed it by changing
var msg ='<%request.getAttribute("error"); %>';
for
var msg = '${error}';
Working as expected now!