【发布时间】:2015-05-22 21:12:02
【问题描述】:
用户在jsp页面中输入搜索
/app/index.jsp
然后单击该页面的提交按钮将处理发送到 servlet 并在单击时更改 url 到 /app/search?id=1234
servlet 处理请求,如果只有一个搜索结果,则它会重定向到该结果的页面,这样就可以正常工作。
但如果没有结果,我想重定向回 /app/index.jsp,但我希望它显示错误(由 servlet 生成)。最简单的方法是什么?
尝试的解决方案
所以在我的 Servlet 中我有:
else
{
System.out.println("You didnt enter anything to search for");
request.setAttribute("error", "You didnt enter anything to search for");
request.getRequestDispatcher("/index.jsp").forward(request, response);
return;
}
(注意调试,以便我可以在我的 tomcat 日志中确认该代码实际上正在运行,它是)
然后我的 index.jsp 说
<h3><%request.getAttribute("error");%></h3>
但是当页面显示时它只是有
<h3></h3>
它从来没有任何东西
解决方案 我错过了一个等号,改为
<%=request.getAttribute("error")%>
修复它。
【问题讨论】:
-
将消息放入请求并转发到搜索页面?
-
@Dave Newton 请展开
-
我不知道如何扩展它;用消息设置请求属性,转发(不是重定向,消息会丢失)到搜索页面,在搜索页面上,如果有消息,显示它。