Java 如何从servlet在jsp中显示警报然后重定向到另一个jsp?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24176684/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to show alert in a jsp from a servlet and then redirect to another jsp?
提问by Xaul Omar Tobar
I tried this but does not display the message only redirectslogin.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?
是否可以显示这样的消息?如果是这样,我做错了吗?
采纳答案by Hemant Rai
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: 20thMarch 2018, 08:19 IST
编辑:2018 年 3 月20日,美国标准时间 08:19
ORwithout 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>");
}
回答by Hemant Rai
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.....
从 Servlet,正常重定向到另一个 jsp,并在 jsp“onload”事件上调用 javascript 函数,该函数将为您提供所需的警报.....
回答by Si Kelly
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
非空语法允许检查参数是否存在
回答by Raju Irale
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);