我正在做一项任务,创建一个简单的博客,用户可以在其中提出问题(帖子),答案可以作为评论给出。
由于我对 Java、REST 和 Jquery 的了解有限,我设法获取帖子列表并将它们显示为表格。
现在,每当用户单击任何帖子时,他都应该被重定向到另一个页面,其中可以显示问题的相应评论。
我已经在 Java 中实现了一个 REST 方法,该方法返回 JSON 响应以及与传递的 post_id 相关的注释。
因此,每当用户单击任何帖子时,他都会被重定向到 REST URL(.../services/comments?postID=1)
并获得以下响应:
[
{
"postID": 1,
"commentID": 8,
"comment": "These are the answers getting added",
"commenterID": 7,
"commentDate": 1442671662000,
"commentVote": 0
}
]
这是我提供 REST 调用的 JAVA 方法:
@GET
@Produces({ MediaType.APPLICATION_JSON })
public List<Comments> getUserComments(@QueryParam("postID") Integer postID) {
Session ses = HibernateUtil.currentSession();
ses.flush();
List<Comments> comments = null;
if(postID != null)
{
comments = ses.createQuery("select c from Comments c where c.postID="+postID+" order by c.commentDate desc").list();
}
HibernateUtil.closeSession();
return comments;
}
同时重定向到 JSP 的“最简单”方法是什么,我可以在其中解析此 JSON 并显示它?
最佳答案
您不需要将页面重定向到 jsp。
您需要的是页面的通用模板(jsp)来显示帖子及其来自 json 的答案。此页面应进行 ajax 调用以获取相应帖子(及其答案)的 json 并将其呈现在页面中。
现在的问题是如何将帖子 id 传递到此页面。
您可以通过设置一个像这样的非 html 标签来做到这一点。 <post_id id="post_id" value=1>
。页面加载后,jquery 将使用此标记(并提取 value
属性)来形成 ajax 调用的 url。
示例
假设您有一个页面来显示所有帖子的列表。此页面看起来像
<a href="post.jsp?post_id=1"> post1</a>
<br>
<a href="post.jsp?post_id=2"> post2</a>
另一个用于显示帖子及其评论的 jsp 页面。我们称之为post.jsp
。这个页面应该得到一个参数post_id
在网址中。该页面将设置标签<post_id>
并使用ajax请求从REST url .../services/comments?postID="+post_id
加载相应的评论.
<body>
<script type="text/javascript">
$(document).ready(
function () {
//extract the post_id from tag value
var post_id = $("post_id").attr("value");
//form the rest url using post_id
var post_url = ".../services/comments?postID="+post_id;
$.ajax(
{
url: post_url,
success: function(data, status, jqXHR, json) {
json_data = JSON.parse(data);
html="";
for(var i=0; i<json_data.length; i++) {
//Comments rendering logic
html+= "<h5>"+json_data[i].comment +"</h5>";
}
$("#container").html(html);
}
}
);
}
);
</script>
<post_id value="<%= request.getParameter("post_id") %>" > </post_id>
<div id="container">
</div>
</body>
关于java - 重定向到 JSP 而不是来自 REST 调用的 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32676744/