2

我有一个问题,如何从 Springs MVC 发送 JSON 对象,以便我可以将其转换为我的 HTML 页面上的 JavaScript 对象。

我以传统方式执行此操作:下面是 Java Servlet 的片段,它设置请求属性并将其转发到 JSP 页面。

   JSONObject jsonObj = new JSONObject();
   jsonObj.put("name","test");
   jsonObj.put("age",24);
   request.setAttribute("jsonObj",jsonObj);
   request.getRequestDispatcher("test.jsp").forward(request,response);

在 JSP 中,我检索为:

   <script type="text/javascript">
    var jsonObj =<%=request.getAttribute("jsonObj"); %>;
    alert("name = "+jsonObj.name+" ; age = "+jsonObj.age); // This will output name and age from the JSON Object
   </script>

所以我需要问的是如何在 Springs MVC 中做同样的事情。如何从 Dispatcher Servlet 发送 JSONObject,并将其转换为我的 JSP 页面中的 JS 对象?

4

4 回答 4

4

使用 ObjectMapper 的一种简单方法。它将从您的对象创建一个 JSON 字符串。并且您可以将其发送到您的视图/jsp。

我放了一个我这样做的控制器的小例子(只是剪断了)。

@Controller
public class UsersSettingsController {

    @Autowired
    UserSettingsDefaultService userSettingsService;


    @RequestMapping(value="/userSettings/dynamic/userSettings", method=RequestMethod.GET)
    public ModelAndView get() throws Exception {
        ModelAndView mav = new ModelAndView();
        ObjectMapper mapper = new ObjectMapper();


    User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    UserSettings userSet = userSettingsService.getUserSettingsByUser(user);

    mav.addObject("userSettingsJSON", mapper.writeValueAsString(userSet));

    mav.setViewName("userSettings/dynamic/filter");


        return mav;
    }
}

或者,您可以像在示例中那样一步一步地在您的 Contoller 中创建 JSON 对象。然后你不需要映射器,只需将字符串发送到你的视图。

在 JSP 中,您将这样的 json 字符串加载到 JS var 中:

var jsonString = '${userSettingsJSON}';

要从 JSON 字符串获取元素或进行解析,请参阅: http: //www.json.org/js.html
我是一个 KnockOut 框架的粉丝,我会用它来做。

于 2012-11-05T08:41:51.970 回答
2

我认为你应该使用ajax(例如jquery),以下是spring mvc

@RequestMapping(value = "/admin/new/list", method = RequestMethod.GET)
@ResponseBody
public List<News> list()
{
  return newsDao.findAll();
}

在 jsp 页面中,您可以使用 ajax util(例如 jquery)

$.ajax({
            type: "GET",
            url: '<c:url value="/admin/new/list"/>',
            cache:false,
            dataType :'json',
            success: function(data){
                 alert(data);               
           }
    });

数据是json对象不知道上面是不是你需要的

于 2012-11-05T09:33:14.253 回答
0

根据您的要求,我建议您使用 JSON 作为数据类型的 AJAX 调用。

例如 :

$.ajax({
                    url: "getFormatIdDescMap?compId="+compId,
                    global: false,
                    type: "POST",
                    dataType:"json",
                    contanttype:'text/json',
                    async:false,
                    error:function(){
                        alert("Error during retrieving the foramt ID List");
                    },
                    success: function(data){                                                
                        //REMOVE ALL THE OLD VALUES OF FORMAT DROP DOWN
                        removeDropDownVals('formatList');

                        var optn;
                        for(var index=0;index<data.formatKeys.length;index++){
                            optn = document.createElement("option");
                            document.getElementById("formatList").options.add(optn);
                            optn.text =data.formatDescs[index];
                            optn.value=data.formatKeys[index];  
                        }
                    }
                });

            });

在上面的代码中,我正在准备一个基于公司 ID 的新格式列表。您可以迭代响应。

它将根据您的要求提供响应文本。但这里请注意,.. 如果您在响应中获得 json 数组,它将包含方括号中的数据,如 ..[1,2,3] 并且如果您在 JSON 对象中获得响应,那么它将以卷曲显示{"data",[1,2,3]} 等大括号。

于 2012-11-05T10:30:47.220 回答
0

一个更简单的方法是在 maven 中包含 Jackson 依赖项并使用 @ResponseBody 返回对象的 JSON 表示,而无需手动编写操作。

看看下面的例子,你不应该写任何 JSON 代码的翻译。

http://www.mkyong.com/spring-mvc/spring-3-mvc-and-json-example/

于 2012-11-05T09:22:38.110 回答