如何从servlet发送消息并在jsp中显示
我正在尝试做一些看起来很小但失败了的事情。我试图在登录失败时将响应消息发送回 jsp 但无法。截至目前,我只能重定向回 jsp,但无法在其上显示来自 servlet 的消息。这是重定向的 servlet 部分:
if (count > 0) {
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
我尝试使用 PrintWriter 和重定向来打印消息,但失败了,因为我无法了解如何在 JSP 中接收消息。我还读到我不应该重定向,而应该从 servlet 转发。我该怎么做?请帮助修复从 servlet 转发的代码补丁以及在 JSP 中接收的代码补丁。谢谢
I'm trying to do something that looks small but it's failing. I'm trying to send a response message back to a jsp when login fails but not being able. As of now I can only redirect back to the jsp but cannot display a message from the servlet on it. This is the servlet part of the redirection:
if (count > 0) {
res.sendRedirect("adminHome.jsp");
} else {
res.sendRedirect("index.jsp");
}
I tried to print a message using PrintWriter and the redirect but failed because I couldn't get how to receive the message in the JSP. I also read that I shouldn't redirect but rather I should just forward from the servlet. How can I do this? Please help with the code patch to forward from servlet as well as that one to receive in JSP. Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您坚持使用重定向而不是转发,那么您有 2 个选择:
将消息作为请求参数传递
这样就可以在JSP中显示如下
它也只在浏览器地址栏中可见,并且您无法通过这种方式传递非标准 Java 对象。
将其存储在会话中
这样您就可以在 JSP 中显示(和删除)它,如下所示:
删除很重要,否则它会在整个会话中保留在那里。
但是,如果您愿意使用转发而不是重定向,它会更优雅:
并在 JSP 中按如下方式显示它
另请参阅:
${}
东西。If you insist to use redirect instead of forward, then you have 2 options:
Pass the message as request parameter
so that you can display it in JSP as follows
It's only visible in the browser address bar as well and you aren't able to pass non-standard Java objects this way.
Store it in session
so that you can display (and remove) it in JSP as follows:
Removing is important, otherwise it sticks there for the entire session.
However, if you're open to using forward instead of redirect, it's more elegant:
and display it as follows in JSP
See also:
${}
things.将消息设置为请求对象的属性:
使用 RequestDispatcher 将请求和响应对象分派到 jsp:
使用表达式语言语法在 JSP 中访问它:
Set your message as an attribute of the request object:
Use a RequestDispatcher to dispatch the request and response objects to the jsp:
Access it in your JSP using Expression Language syntax:
您可以将消息保存在请求中,然后转发到 jsp 而不是重定向。
然后在 jsp 页面上您可以通过请求访问该消息。
You can save the message in the request and then forward to the jsp rather than redirect.
Then on the jsp page you have access to the message via the request.