繁体   English   中英

将 bean 数据从 servlet 传递到 jsp 的问题

[英]problem with passing bean data from servlet to jsp

我有 2 个 jsp 页面,一个称为 MyPage.jsp,另一个称为 View.jsp。 View.jsp 具有树形结构。 MyPage.jsp 有一些称为数字和设计的文本字段,需要通过 servlet 通过 bean 填充。 单击 View.jsp 中的任何树节点时,应使用设置的文本字段值呈现 MyPage.jsp。 现在发生的事情是因为 MyPage.jsp 被调用了两次,即一次在 View.jsp 中(在 ajax 函数中),第二次在 servlet 的请求调度程序中,因此在 servlet 中设置的 bean 值丢失了。 请提出一种更好的方法,以便在整个过程中保留这些值,并且在单击树节点 MyPagejsp 时会使用设置的字段值呈现。

responseBean.setNumber("220");
responseBean.setDesign("xyz");
response.setContentType("text/html");                        
response.setCharacterEncoding("UTF-8");
request.setAttribute("responseBean", responseBean);
RequestDispatcher requestDispatcher = getServletContext().getRequestDispatcher("/MyPage.jsp");
requestDispatcher.include(request, response);
response.getWriter().write("Success");

jsp 页面从其中调用 MyPage.jsp 并设置 bean 值具有以下代码

查看.jsp

$.ajax({
 url : AJAX_SERVLET,
type: "GET",
data: "Number="+node.data.title,
success : function(output) {                                
$("[id=content]").attr("src", '/Test-portlet/MyPage.jsp');
}
});
}

MyPage.jsp

<jsp:useBean id="responseBean" class="com.web.bean.ResponseBean" scope="request">

<jsp:setProperty name="responseBean" property="*"/>

</jsp:useBean>
<body>
<%System.out.println("Values"+responseBean.getNumber()); %>
</body>

在上面的 MyPage.jsp 代码中,System.out.println 打印了两次值; 一次作为值 202,第二次作为值 null。 由于它将原始值替换为 null 只是因为 MyPage.jsp 被调用两次,因此第二次值丢失。 请帮忙

我相信您会混淆/误解一些基本概念,特别是 HTTP 的工作原理以及 Ajax 的工作原理。

这里发生的是您有效地触发了两个 HTTP 请求。 一个是$.ajax() ,另一个是element.attr('src', url) 每个请求都会导致创建和设置一个完全不同的 bean 实例。 您完全忽略了$.ajax()请求回调中的 bean 数据。 我不确定 HTML 元素[id=content]代表什么,但我猜它是一个<iframe> 这并不完全正确。

您最终应该会有效地触发一个 HTTP 请求。 基本上有2个解决方案:

  1. 忘记$.ajax()并通过element.attr('src', url)发送请求。

     $("[id=content]").attr("src", "/Test-portlet/MyPage.jsp?number=" + encodeURIComponent(node.data.title));

    您还可以将 URL 更改为一个 servlet,以便您有更多的预处理控制,最后使用RequestDispatcher#forward()而不是include() 不要将 HTML 写入 servlet 中的响应。 让 JSP 来做吧。

  2. 忘记<iframe>的事情并完全通过 Servlet/Ajax 处理响应,而无需 JSP 的干预。 您需要将 bean 转换为其他数据格式,以便通过 JavaScript/jQuery 轻松解析。 我建议为此使用 JSON 。

     $.get(AJAX_SERVLET, { "number": node.data.title }, function(response) { $("#number").text(response.number); $("#design").text(response.design); });

    例如在 HTML

     <div id="number"></div> <div id="design"></div>

    并在 servlet

     //... (create ResponseBean the way as you want) String json = new Gson().toJson(responseBean); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json);

也可以看看:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM