How to show alert in a jsp from a servlet and then

2020-02-09 18:57发布

I tried this but does not display the message only redirects login.jsp

<form method="post" action="Login_Servlet" >
  <input name="idUsuario" type="text"/>
  <input  name="password" type="password" />
  <button type="submit">Entrar</button>
</form>

Login_Servlet

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String userid= request.getParameter("idUser");        
String password = request.getParameter("password");
Login_Service login_Service = new Login_Service();
boolean result = login_Servicio.aut(userid, password);
Usuario user = login_Servicio.getUsuariosByUsuario(userid);
    if(result == true){
       request.getSession().setAttribute("user", user);            
       response.sendRedirect("vistas/Inicio.jsp");
    }
     else{
       out.println("<script type=\"text/javascript\">");
       out.println("alert('User or password incorrect');");
       out.println("</script>");
       response.sendRedirect("index.jsp");    
    }

Is it possible to display a message like this? if so I'm doing wrong?

4条回答
家丑人穷心不美
2楼-- · 2020-02-09 19:46

You may possibly do this:

else
{
   out.println("<script type=\"text/javascript\">");
   out.println("alert('User or password incorrect');");
   out.println("location='index.jsp';");
   out.println("</script>");
}

Edited: 20th March 2018, 08:19 IST

OR without using js

else {
   out.println("<meta http-equiv='refresh' content='3;URL=index.jsp'>");//redirects after 3 seconds
   out.println("<p style='color:red;'>User or password incorrect!</p>");
}
查看更多
等我变得足够好
3楼-- · 2020-02-09 19:46

You could redirect to your jsp but pass a message to be displayed:

request.setAttribute("loginError","Incorrect password");

Then in the jsp:

 <c:if test="${not empty loginError}">
    <script>
    window.addEventListener("load",function(){
         alert("${loginError}");
    }
    </script>
</c:if>

The not empty syntax allows checking for the existence of a parameter

查看更多
姐就是有狂的资本
4楼-- · 2020-02-09 19:56
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<script type=\"text/javascript\">");
pw.println("alert('Invalid Username or Password');");
pw.println("</script>");
RequestDispatcher rd=request.getRequestDispatcher("userlogin.jsp");
rd.include(request, response);
查看更多
家丑人穷心不美
5楼-- · 2020-02-09 20:01

From Servlet, redirect to another jsp normally as you do, and on jsp "onload" event call a javascript function which will give you the alert you need.....

查看更多
登录 后发表回答