使用servlet返回json对象 [英] return json object using servlet
问题描述
我有一个servlet.它的工作方式是-我发送动作名称,servlet创建动作对象,执行某些任务,然后将字符串view
作为结果返回-我应该发送给用户的页面. Servlet对于doGET
和doPost
都是相同的.
I've got a servlet. It works like this - I send action-name, servlet create action-object, perform some tasks in action, then return string view
as result - to what page I should send user. Servlet works the same for doGET
and for doPost
.
String name = getActionName(req);
Action action = (Action) pico.getComponentInstance(name);
String view = action.exec(req, resp);
// router
if (view.startsWith("redirect:")) {
resp.sendRedirect(view.substring("redirect:".length(),
view.length()));
} else {
getServletContext().getRequestDispatcher(
"/" + view + ".jsp").forward(req, resp);
}
我有AjaxAction,我从请求中获取值,从数据库中获取对象,将其转换为json字符串.但是如何从行动中恢复呢?操作返回字符串,表示应该将用户发送到的下一页.我将他发送到main
页面.
I've got AjaxAction where I get value from request, get object from database, transform it into json string. But how to return it from action? Action returns string, represents next page where user should be sent. I send him to main
page.
String requestId = req.getParameter("requestId");
Long id = Long.valueOf(requestId);
Request item = requestDao.read(id);
String json = "";
json = new Gson().toJson(item);
resp.setContentType("application/json");
resp.setCharacterEncoding("UTF-8");
try {
resp.getWriter().write(json);
} catch (IOException e) {
e.printStackTrace();
}
return "main";
每次更改<select>
(使用id = "re"
)中的值时,我都会发送JSON对象请求.
I send request for JSON object every time I change value in <select>
(with id = "re"
).
$("#re").change(function() {
var $id = $('#re').val();
$.get('AjaxAction.do', {
requestId : $id
}, function(respJSON) {
alert(respJSON);
$.each(respJson, function(key, value) {
$('#' + key).val(value);
});
});
});
但是alert
都不会出现,也不会更改#+ key中的值.因此,似乎功能无法正常工作.
那么如何正确地从Action返回JSON对象呢?
我调试器AjaxAction
创建对象和return "main";
.
But neither alert
appear nor value in #+key change. So it seems function doesn't work.
So how properly return JSON object from Action?
I debugger AjaxAction
creates object and return "main";
.
推荐答案
- 将
return "main";
更改为return null;
- 之后,您将能够在同一页面上获得ajax响应和alert();
- 如果需要,您可以执行
document.location="anotherpage";
而不是警报,现在可以将用户重定向到另一个页面
- Change
return "main";
toreturn null;
- After that you will be able to get ajax response and alert() on the same page;
- Instead of alert you can redirect user to another page now if needed by doing
document.location="anotherpage";
这篇关于使用servlet返回json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!