简体   繁体   English

如何从servlet在jsp中显示警报然后重定向到另一个jsp?

[英]How to show alert in a jsp from a servlet and then redirect to another jsp?

I tried this but does not display the message only redirects login.jsp我试过这个但不显示消息只重定向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登录_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?如果是这样我做错了吗?

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: 20 th March 2018, 08:19 IST编辑:2018 年 3 月 20,美国标准时间 08:19

OR without using js不使用 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>");
}

You could redirect to your jsp but pass a message to be displayed:您可以重定向到您的 jsp 但传递要显示的消息:

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

Then in the jsp:然后在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非空语法允许检查参数是否存在

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);

从 Servlet,正常重定向到另一个 jsp,并在 jsp“onload”事件上调用 javascript 函数,该函数将为您提供所需的警报.....

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM