使用 Jackson 通过 AJAX 从 Spring MVC 控制器返回 java.util.List
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11856005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Returning a java.util.List from a Spring MVC controller via AJAX using Hymanson
提问by Tiny
Based on my questionposted a few days ago, I realized that SimpleFormController
is inappropriate for handling Ajax requests. Therefore, I'm migrating my application towards annotated controllers.
根据我几天前发布的问题,我意识到这SimpleFormController
不适合处理 Ajax 请求。因此,我正在将我的应用程序迁移到带注释的控制器。
I'm trying to return a java.util.List
from Oracle database using Spring MVC 3.0.2 with Hibernate via Ajax using Hymanson 1.9.8(its download page) but I haven't yet worked with JSON in any technology. I have read up some tutorials/articles but I couldn't get the idea of how to return such complex data structures and parse them using JSON in Spring. I'm trying to learn JSON-like concepts first.
我正在尝试java.util.List
使用 Spring MVC 3.0.2 和 Hibernate 通过 Ajax 使用Hymanson 1.9.8(其下载页面)从 Oracle 数据库返回一个,但我还没有在任何技术中使用 JSON。我已经阅读了一些教程/文章,但我不知道如何返回如此复杂的数据结构并在 Spring 中使用 JSON 解析它们。我首先尝试学习类似 JSON 的概念。
What basically I'm trying is when a country is selected from a country select box, the states corresponding to that country should be populated from the database via Ajax. I don't have precise idea about how to return a java.util.List
over an Ajax response, how to parse it and again use it in Java code. I'm only upto the following level.
基本上我正在尝试的是,当从国家/地区选择框中选择一个国家/地区时,应通过 Ajax 从数据库中填充与该国家/地区相对应的州。我不知道如何java.util.List
通过 Ajax 响应返回 a ,如何解析它并在 Java 代码中再次使用它。我只达到以下水平。
JS code.
JS代码。
function getStates(countryId)
{
$.ajax({
datatype:"json",
type: "POST",
url: "/wagafashion/ajax/TempAjax.htm",
data: "countryId=" + countryId,
success: function(response)
{
$('#msg').html(response);
$('#stateList').val('');
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
The method in the Spring controller class which is invoked when the Ajax request is made on the onchange
event of the country select box.
Spring 控制器类中的方法onchange
,在国家选择框的事件上发出 Ajax 请求时调用。
@RequestMapping(method=RequestMethod.POST, value="ajax/TempAjax")
public @ResponseBody List<StateTable> getStateList(@ModelAttribute("tempBean") TempBean tempBean, BindingResult error, Map model, HttpServletRequest request, HttpServletResponse response)
{
Session session=NewHibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<StateTable>list=session.createQuery("from StateTable where country.countryId=:countryId order by stateId").setParameter("countryId", new BigDecimal(request.getParameter("countryId"))).list();
session.flush();
session.getTransaction().commit();
return list;
}
The state select box I need to populate with the list of states returned by the Ajax response using a <c:forEach></c:forEach>
loop of EL.
我需要使用<c:forEach></c:forEach>
EL 循环用 Ajax 响应返回的状态列表填充状态选择框。
<form:select path="cmbState" class="validate[required] text-input tooltip" title="Mandatory select field.">
<form:option value="">Select</form:option>
<c:forEach items="${stateList}" var="row">
<c:choose>
<c:when test="${row.stateId==param['stateId'] and deselectCombo!=1}">
<form:option value="${row.stateId}" selected="selected">${row.stateName}</form:option>
</c:when>
<c:otherwise>
<form:option value="${row.stateId}">${row.stateName}</form:option>
</c:otherwise>
</c:choose>
</c:forEach>
</form:select>
<font style="color: red"><form:errors path="stateId"/></font><br/>
I could only make Ajax request and response successfully. Nothing more I could understand from those tutorials found over the internet. More precisely, how can I use the Ajax response in the items
attribute of the preceding <c:forEach><c:forEach>
loop such as items="${stateList}"
?
我只能成功地进行 Ajax 请求和响应。从互联网上找到的那些教程中,我无法理解更多内容。更准确地说,如何items
在前面的<c:forEach><c:forEach>
循环的属性中使用 Ajax 响应,例如items="${stateList}"
?
Could you give me some hint/idea how can I return a list of data and use it in the preceding loop to populate the state select box? Could you please lead me some steps ahead from here?
你能给我一些提示/想法如何返回数据列表并在前面的循环中使用它来填充状态选择框?你能带我从这里向前走几步吗?
I'm using NetBeans 6.9.1 (not Eclipse). In some tutorials about Marvan projects in Eclipse, it was mentioned that the pom.xml
file is required to configure to include <dependencies></dependencies>
(Hymanson dependency). There is no such thing like pom.xml
in my project in NetBeans. Is it required to configure somewhere in some xml file in NetBeans such as the one mentioned here?
我使用的是 NetBeans 6.9.1(不是 Eclipse)。在一些关于 Eclipse 中 Marvan 项目的教程中,提到pom.xml
需要配置文件以包含<dependencies></dependencies>
(Hymanson 依赖)。pom.xml
在我的 NetBeans 项目中没有这样的东西。是否需要在 NetBeans 中的某个 xml 文件中的某处进行配置,例如此处提到的那个?
回答by hyness
The strategy you should use is to make the AJAX call from jQuery, take the JSON response and use it to update the form dynamically from jQuery not java. The only use I can see for the JSP tags would be to render the page when it loads. Here is how I would approach this...
您应该使用的策略是从 jQuery 进行 AJAX 调用,获取 JSON 响应并使用它从 jQuery 而不是 java 动态更新表单。我可以看到 JSP 标记的唯一用途是在页面加载时呈现页面。这是我将如何处理这个......
Change your controller to use a GET instead of a POST. For one, it is incorrect in REST to use a POST here (you are only retrieving data, not altering it). But, more importantly, it will make it easier for you to test the controller by simply putting the URL into a browser to see the JSON response. Using the
@ResponseBody
annotation and including Hymanson on the classpath should produce a JSON response here (unless you have some Hibernate lazy loading issues).Once you verify the controller is returning JSON, update your jQuery success handler to dynamically populate the dropdown. This should be relatively easy. Test this in the browser.
Write a new controller to handle this form submission. In this controller, just include a method to return the list and annotate it as
@ModelAttribute("stateList")
. This will make the list available for use in your<c:forEach>
loop to render the page on load. You will have another method that will handle the actual form submission in the same controller.
更改您的控制器以使用 GET 而不是 POST。一方面,在 REST 中使用 POST 是不正确的(您只是检索数据,而不是更改数据)。但是,更重要的是,通过简单地将 URL 放入浏览器以查看 JSON 响应,您可以更轻松地测试控制器。使用
@ResponseBody
注释并在类路径中包含 Hymanson 应该会在此处生成 JSON 响应(除非您有一些 Hibernate 延迟加载问题)。验证控制器返回 JSON 后,更新 jQuery 成功处理程序以动态填充下拉列表。这应该相对容易。在浏览器中测试一下。
编写一个新的控制器来处理这个表单提交。在这个控制器中,只需包含一个方法来返回列表并将其注释为
@ModelAttribute("stateList")
. 这将使列表可用于<c:forEach>
循环中以在加载时呈现页面。您将拥有另一种方法来处理同一控制器中的实际表单提交。
Another thing to consider is to have better separation of concerns by putting the database code in its own service or repository. It's a bad practice to do data access in a controller in an MVC architecture. As a bonus, you won't need to duplicate any code to load the list in two different controllers.
另一件要考虑的事情是通过将数据库代码放在自己的服务或存储库中来更好地分离关注点。在 MVC 架构中的控制器中进行数据访问是一种不好的做法。作为奖励,您无需复制任何代码即可在两个不同的控制器中加载列表。
Also, look into Spring's @Transactional
declarative transaction handling. That way you won't need to write any code for transaction handling. You can also simply inject the SessionFactory
instead of writing your own HibernateUtils
.
此外,请查看 Spring 的@Transactional
声明式事务处理。这样你就不需要为事务处理编写任何代码。您也可以简单地注入SessionFactory
而不是编写自己的HibernateUtils
.
Hope that helps
希望有帮助
Edit :In REST, here are HTTP methods mapped to their corresponding CRUD actions.
编辑:在 REST 中,这里是映射到其相应 CRUD 操作的 HTTP 方法。
- POST- Create
- GET- Retrieve
- PUT- Update
- DELETE- Delete
- POST- 创建
- GET- 检索
- PUT- 更新
- 删除- 删除
回答by rajesh kakawat
you should try to your option list in ajax response instead of json like below one
您应该尝试在 ajax 响应中使用您的选项列表,而不是像下面这样的 json
<option value="1">Mumbai</option>
<option value="2">Delhi</option>
<option value="3">Kerala</option>
<option value="4">Rajasthan</option>
and then your should add it to your select box liek below one
然后你应该把它添加到你的选择框下面
function getStates(countryId)
{
$.ajax({
datatype:"html",
type: "POST",
url: "/wagafashion/ajax/TempAjax.htm",
data: "countryId=" + countryId,
success: function(response)
{
$('#stateList').html(response);
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
or you can create json on serverside like below one
或者你可以像下面这样在服务器端创建 json
[{"key":1, "value": "Mumbai"}, {"key":2, "value":"Delhi"}....]
and in javascript code
并在 javascript 代码中
function getStates(countryId)
{
$.ajax({
datatype:"html",
type: "POST",
url: "/wagafashion/ajax/TempAjax.htm",
data: "countryId=" + countryId,
success: function(response)
{
if(response !=''){
jQuery("#stateList").html("");
jQuery.each(response, function(index,item) {
jQuery("#stateList").append(jQuery("<option />")
.attr("value",item.value)
.text(item.key));
});
}
},
error: function(e)
{
alert('Error: ' + e);
}
});
}