2012-11-05 32 views
1

我有一個問題,我如何從泉MVC發送JSON對象,以便我可以將其轉換爲我的HTML頁面上的JavaScript對象。Springs MVC JSON響應並將其轉換爲JS對象

以傳統方式執行此操作:下面是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> 

所以我要問我該怎麼做相同的泉MVC的東西。如何從Dispatcher Servlet發送JSONObject,並將其轉換爲JSP頁面中的JS對象?

回答

4

一個簡單的方法來使用ObjectMapper來做到這一點。它會從你的對象中創建一個JSON字符串。而且你可以發送到你的view/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對象,就像你在你的例子中一樣。然後你不需要Mapper,只需要將String發送到你的View。

在JSP中加載的JSON字符串像這樣成JS變種:

var jsonString = '${userSettingsJSON}'; 

要想從JSON字符串元素或解析,請參閱:http://www.json.org/js.html
我是一個KnockOut框架風扇會做它。

+0

優秀的答案。那正是我在找的東西。 –

+0

歡迎您! – derlinuxer

0

更簡單的方法是在Maven中包含Jackson依賴項,並使用@ResponseBody返回對象的JSON表示,而無需手動編寫操作。

看看下面的例子,你不應該寫任何轉換到JSON代碼。

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

+0

先生..謝謝你,但我已經看過這個例子,它正在返回一個JSON對象,我需要它被捕獲爲一個JavaScript對象,以便我可以查看並相應地使用jQuery在我的DOM上/ JS。 –

+0

當您在'.ajax'調用中指定'type:'json'時,jQuery會自動將JSON轉換爲JS對象。有關詳細信息,請參閱jQuery文檔。 – nickdos

+0

尊敬的主席先生,我需要返回JSP頁面作爲響應,但此示例返回的是JSON對象而不是JSP頁面。我非常清楚jQuery可以將JS對象作爲JS對象來捕獲。 –

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對象 我不知道上面是什麼你需要

+0

我不是在尋找AJAX Call,我知道這是另一種方式。但這不是我想要的。 –

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]}。