【问题标题】:How does jsp show additional data based on processing done by servlet called by jsp pagejsp如何根据jsp页面调用的servlet完成的处理显示附加数据
【发布时间】: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 请展开
  • 我不知道如何扩展它;用消息设置请求属性,转发(不是重定向,消息会丢失)到搜索页面,在搜索页面上,如果有消息,显示它。

标签: java jsp servlets


【解决方案1】:

您应该使用错误消息设置请求;

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

更多详情,您可以查看我的答案,其中有类似的scenario

【讨论】:

  • 谢谢所以我做了这个 request.setAttribute("error","Error Message"); request.getRequestDispatcher("/index.jsp").forward(request, response);返回;在我的jsp中我有

    但一条消息永远不会显示?
  • @PaulTaylor 请在您的问题中分享您的代码作为编辑;所以我可以好好检查一下。
  • 认为它在 jsp 中缺少一个“=”
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-25
相关资源
最近更新 更多