将 JSON 对象从控制器传递到视图(jsp)

发布于 2024-11-07 00:54:59 字数 1776 浏览 0 评论 0原文

我正在尝试从控制器将 JSON 对象发送到我的视图,但无法发送它。 请帮帮我!

我正在使用以下代码

public class SystemController extends AbstractController{

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView("SystemInfo", "System", "S");

        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonResult = new JSONObject();

        jsonResult.put("JVMVendor", System.getProperty("java.vendor"));
        jsonResult.put("JVMVersion", System.getProperty("java.version"));
        jsonResult.put("JVMVendorURL", System.getProperty("java.vendor.url"));
        jsonResult.put("OSName", System.getProperty("os.name"));
        jsonResult.put("OSVersion", System.getProperty("os.version"));
        jsonResult.put("OSArchitectire", System.getProperty("os.arch"));

        response.getWriter().write(jsonResult.toString());
     //   response.getWriter().close();

        return mav;             // return modelandview object
    }
}

,在视图端我正在使用

<script type="text/javascript">

Ext.onReady(function(response) {
     //Ext.MessageBox.alert('Hello', 'The DOM is ready!');
     var showExistingScreen = function () {
        Ext.Ajax.request({
            url                     : 'system.htm',
            method                  : 'POST',
            scope                   : this,
            success: function ( response ) {
                alert('1');
                var existingValues = Ext.util.JSON.decode(response.responseText);
                alert('2');
              }
        });
    };

    return showExistingScreen();
});

I am trying to send JSON object to my view from controller but unable to send it.
Please help me out!

I am using following code

public class SystemController extends AbstractController{

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mav = new ModelAndView("SystemInfo", "System", "S");

        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        JSONObject jsonResult = new JSONObject();

        jsonResult.put("JVMVendor", System.getProperty("java.vendor"));
        jsonResult.put("JVMVersion", System.getProperty("java.version"));
        jsonResult.put("JVMVendorURL", System.getProperty("java.vendor.url"));
        jsonResult.put("OSName", System.getProperty("os.name"));
        jsonResult.put("OSVersion", System.getProperty("os.version"));
        jsonResult.put("OSArchitectire", System.getProperty("os.arch"));

        response.getWriter().write(jsonResult.toString());
     //   response.getWriter().close();

        return mav;             // return modelandview object
    }
}

and in the view side I am using

<script type="text/javascript">

Ext.onReady(function(response) {
     //Ext.MessageBox.alert('Hello', 'The DOM is ready!');
     var showExistingScreen = function () {
        Ext.Ajax.request({
            url                     : 'system.htm',
            method                  : 'POST',
            scope                   : this,
            success: function ( response ) {
                alert('1');
                var existingValues = Ext.util.JSON.decode(response.responseText);
                alert('2');
              }
        });
    };

    return showExistingScreen();
});

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

静待花开 2024-11-14 00:54:59

为了将 JSON 发送回客户端,我成功地使用了以下解决方案:

1) 客户端(浏览器)向我的 SpringMVC 控制器发送包含 JSON 格式值(但也可以使用 GET)的 AJAX POST 请求。

$.postJSON("/login", login, function(data)
{
    checkResult(data);
});

2)SpringMVC控制器方法签名:

@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody Map<String, String> 
login(@RequestBody LoginData loginData, 
HttpServletRequest request, HttpServletResponse response)

@ResponseBody是关键,它“...指示返回类型应该直接写入HTTP响应主体(而不是放置在模型中,或解释为视图名称)”。 [Spring 参考文档]
LoginData 是一个简单的 POJO 容器,用于存储来自客户端请求的 JSON 值,如果您将 jackson jar 文件(我使用 jackson-all-1.7.5.jar)放入类路径中,则会自动填充。
作为控制器方法的结果,我创建了一个 hashMap。 (例如,使用键“error”或“view”以及适当的值)。然后,该映射会自动序列化为由客户端解释的 JSON(同样是正常的 html 页面,包括 Javascript)

function checkResult(result)
{
    if (result.error)
    {
      // do error handling
    }
    else
    {
      // use result.view
    }
}

For sending JSON back to the client I successfully use the following solution:

1) client (browser) sends an AJAX POST containing JSON formatted values (but GET also possible) request to my SpringMVC controller.

$.postJSON("/login", login, function(data)
{
    checkResult(data);
});

2) The SpringMVC controller method signature:

@RequestMapping(value = "/login", method = RequestMethod.POST)
public @ResponseBody Map<String, String> 
login(@RequestBody LoginData loginData, 
HttpServletRequest request, HttpServletResponse response)

@ResponseBody is the key, it "...indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name)." [Spring Reference Doc]
LoginData is a simple POJO container for the JSON values from the client request, filled automatically if you put a jackson jar file (I use jackson-all-1.7.5.jar) into your classpath.
As result of the controller method, I create a hashMap<String, String>. (e.g. with keys 'error' or 'view' and appropriate values). This map is then automatically serialized into JSON which is interpreted by the client (again normal html page incl. Javascript)

function checkResult(result)
{
    if (result.error)
    {
      // do error handling
    }
    else
    {
      // use result.view
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文