Reputation: 7768
I have written a code to display an error message if the user login fails. The servlet code is as follows:
HttpSession session = request.getSession(true);
/*User class is a Java bean with an isValid attribute*/
User user= new User();
if (!user.isValid()) {
request.setAttribute("errorMessage"," Invalid Parameters!");
request.getRequestDispatcher("RegistrationPage.jsp").forward(request, response);
}
// RegistrationPage.jsp file code snippet is below
<script>
function loginFailure() {
System.out.println("Invalid parameters");
if(request.getParameter("errorMessage") != null) {
alert("<%= request.getParameter("errorMessage") %>");
}
</script>
<body onload="loginFailure()">
</body>
I cannot understand why the page is not displaying the alert message when there is a failure in the login. It does go into the method for loginFailure and to the alert function as well.
Upvotes: 0
Views: 331
Reputation: 7768
Scriptlet and javascript to display this message:
<%
String message = (String) request.getAttribute("errorMessage");
if (message != null) {
%>
<script>
alert('<%=message%>');
</script>
<%
}else{
%>
<script>
alert("Login Successfull");
</script>
<%
}
%>
Upvotes: 0
Reputation: 402
First, as @PM 77-1 says, you need to do getAttribute()
not getParameter()
. Also, don't you want that System.out
to execute only if the conditional is true? But the larger problem is that you're mixing up your Java and JavaScript. Your conditional if(request.getParameter("errorMessage") != null)
, presumably meant to be executed server-side as Java code, isn't within scriptlet tags, so the JavaScript interpreter will try to execute it and fail. Seems like what you want to be doing is this:
<script>
function loginFailure() {<%
if(request.getParameter("errorMessage") != null) {
System.out.println("Invalid parameters");
%>
alert("<%= request.getAttribute("errorMessage") %>");
<%
}%>
</script>
That's the simplest fix. Although you don't really want to be mingling server-side and client-side code to the extent you are either (i.e., putting any Java code within a JavaScript function). Better to define a var errorMessage
outside the function, like var errorMessage="<%=request.getAttribute("errorMessage")==null?"":request.getAttribute("errorMessage").toString()%>"
and then use a JavaScript conditional (not Java, as it seems you were trying to do) which alerts the error message only if its length is greater than zero.
Upvotes: 1