Eman Hassan
Eman Hassan

Reputation: 23

How can I alert message in Servlet code and sendredirect to JSP page?

I am trying to make a simple login page to deal with database using JSP, servlet with MVC concept and Data Access Object(DAO) and I am new in this. My problem now that I need to alert a box message in servlet if the user enters invalid name and password and sendRedirect to login.jsp page again. I set flag to be 1 if the user valid then do this if-check

if(validUserFlage == 1)
    response.sendRedirect("User_Manipulation_Interface.jsp");
else {   
    //Here i want to alert message cause user invalid ??
    response.sendRedirect("Admin_And_User_Login_Form.jsp");
}

searching for this i find this answer but i can`t understand how can i do it the answer i found: (( With send redirect you cant display the message where you want in the code. So as per me there might be two approaches. Display a message here and use include of requestdispatcher instead of send redirect or else pass some message to admin.jsp and display the message there. ))

Upvotes: 2

Views: 28987

Answers (3)

Nishanth Thomas
Nishanth Thomas

Reputation: 31

In servlet
    String strExpired = (String) session.getAttribute("Login_Expired");
response.sendRedirect("jsp/page.jsp");

In jsp 
<%
String strExpired = (String) session.getAttribute("Login_Expired");
out.print("alert('Password expired, please update your password..');");

%>

Upvotes: 0

Haresh Chaudhary
Haresh Chaudhary

Reputation: 4400

You can set the Parameters like errormsg in the servlet page and add it to the ri-direct object. Then you can check that variable errormsg and if it is null then the username is correct else the username is incorrect..

In Servlet Code:
if(username.equal(databaseusername))

{
RequestDispatcher rd = request.getRequestDispatcher("NextPage.jsp");

req.setAttribute("errormsg", "");

rd.forward(request, response);  

}

else

{

RequestDispatcher rd = request.getRequestDispatcher("login.jsp");

req.setAttribute("errormsg", "Wrong Username or Password");

rd.forward(request, response);  

}

In JSP code:

<%

String msg=req.getAttribute("errormsg").toString();

if(!msg.equals(""))

{

// Print here the value of Msg.

}


%>

Upvotes: 2

Jigar Joshi
Jigar Joshi

Reputation: 240880

Set a flag parameter like this,

 response.sendRedirect("Admin_And_User_Login_Form.jsp?invalid=true");

on jsp

<c:if test=${invalid eq 'true'}">invalid credentials</c:if>

Upvotes: 3

Related Questions