如何从servlet发出消息并在jsp中显示 [英] how to message from servlet and display in jsp
问题描述
我正在尝试做一些看起来很小但失败的事情.登录失败但无法登录时,我正在尝试将响应消息发送回jsp.到目前为止,我只能重定向回jsp,但不能在其上显示来自servlet的消息.这是重定向的servlet部分:
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");
}
我尝试使用PrintWriter和重定向来打印消息,但是失败了,因为我无法在JSP中获得如何接收消息的方法.我还读到我不应该重定向,而应该从servlet转发.我怎样才能做到这一点?请帮助从Servlet转发的代码补丁以及在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
推荐答案
如果您坚持使用重定向而不是转发,那么您有2个选择:
If you insist to use redirect instead of forward, then you have 2 options:
-
将消息作为请求参数传递
Pass the message as request parameter
String message = "hello";
res.sendRedirect("adminHome.jsp?message=" + URLEncoder.encode(message, "UTF-8"));
以便您可以在JSP中将其显示如下
so that you can display it in JSP as follows
<p>Message: ${param.message}</p>
它也仅在浏览器地址栏中可见,并且您不能以这种方式传递非标准Java对象.
It's only visible in the browser address bar as well and you aren't able to pass non-standard Java objects this way.
将其存储在会话中
String message = "hello";
req.getSession().setAttribute("message", message);
res.sendRedirect("adminHome.jsp");
,以便您可以在JSP中显示(并删除)它,如下所示:
so that you can display (and remove) it in JSP as follows:
<p>Message: ${message}</p>
<c:remove var="message" scope="session" />
删除非常重要,否则整个会话都将粘贴在那里.
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:
String message = "hello";
req.setAttribute("message", message);
req.getRequestDispatcher("/adminHome.jsp").forward(req, res);
并在JSP中如下显示
<p>Message: ${message}</p>
另请参见:
- 我们的Servlets Wiki页面-包含一个Hello World,它也可以处理消息传递
- EL Wiki页面-解释所有有关
${}
的事情. - Our Servlets wiki page - contains a Hello World which also treats messaging
- EL wiki page - explains all about those
${}
things.
See also:
这篇关于如何从servlet发出消息并在jsp中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!