jsp 如何根据 jsp 页面调用的 servlet 完成的处理显示附加数据

How does jsp show additional data based on processing done by servlet called by jsp page

用户在 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")%>

已修复。

您应该设置带有错误消息的请求;

request.setAttribute("errorMsg", "Error:No users find");
RequestDispatcher rd = null;
rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);

更多细节,你可以查看我的答案,其中有类似的scenario