如何使用从 servlet 到 JSP 获取数据
我是 Java 服务器编程新手,我正在尝试使用 Google 应用程序引擎。
以下代码位于 servlet 中:
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setAttribute("message", "Hi from servlet!");
req.getRequestDispatcher("/my_page.jsp").forward(req, resp);
}
以下代码位于 my_page.jsp
中:
<%= request.getAttribute("message") %>
我希望在结果页面上看到 Hi from servlet!
,我看到 <代码>空。
(如果我尝试使用 ${message}
,我根本得不到任何输出)
从 servlet 获取数据到 JSP 的正确方法是什么?
I'm new to Java server programming, and I'm trying to use Google app engine.
The following code is in a servlet:
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setAttribute("message", "Hi from servlet!");
req.getRequestDispatcher("/my_page.jsp").forward(req, resp);
}
And the following code is in my_page.jsp
:
<%= request.getAttribute("message") %>
Where I would expect to see Hi from servlet!
on the resulting page, I see null
.
(If I try using ${message}
, I get no output at all)
What is the correct way to get data from a servlet to a JSP?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要让请求 URL(您在浏览器地址栏中看到的 URL)指向与
web.xml
中配置的 servlet 的 URL 模式相匹配的 URL,而不是指向JSP 文件本身。最好将 JSP 放在/WEB-INF
文件夹中,这样您就不会在不调用 servlet 的情况下“意外”调用它。顺便说一句,
${message}
是正确的方法,应该优于老式的 scriptlet。You need to let the request URL (the one as you see in browser's address bar) point to an URL which matches the URL pattern of the servlet as configured in
web.xml
, not to the URL of the JSP file itself. Best would be to put the JSP in/WEB-INF
folder so that you can't "accidently" invoke it without invoking the servlet.By the way, the
${message}
is the correct way and should be preferred over old fashioned scriptlets.