2012-04-17 67 views
1

道歉,如果這是重複的,但我找不到具體的例子。springmvc使用json響應

我在springmvc中有以下控制器。

import java.text.DateFormat; 
import java.util.Date; 
import java.util.Locale; 

import org.slf4j.Logger; 
import org.slf4j.LoggerFactory; 
import org.springframework.stereotype.Controller; 
import org.springframework.ui.Model; 
import org.springframework.web.bind.annotation.RequestMapping; 
import org.springframework.web.bind.annotation.RequestMethod; 

/** 
* Handles requests for the application home page. 
*/ 
@Controller 
public class HomeController { 

    private static final Logger logger = LoggerFactory.getLogger(HomeController.class); 

    /** 
    * Simply selects the home view to render by returning its name. 
    */ 
    @RequestMapping(value = "/", method = RequestMethod.GET) 
    public String home(Locale locale, Model model) { 
     logger.info("Welcome home! the client locale is "+ locale.toString()); 

     Date date = new Date(); 
     DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); 

     String formattedDate = dateFormat.format(date); 

     model.addAttribute("serverTime", formattedDate); 

     return "main"; 
    } 

} 

這意味着我可以再訪問$ {serverTime},我的問題是,有沒有方法可以讓我得到這個響應是一個JSON響應,而不必硬編碼在這個控制器的所有JSON的轉換代碼。有沒有一種方法,我可以只是把一些XML的配置,所以它會知道轉換回應說......

{「serverTime」:「12 12 2012」}(忽略臉,這可能不是在正確的日期格式)

我應該提到,「主」是視圖(main.jsp)的名稱,所以我想保持它的工作方式相同。

回答

1

@ResponseBody註釋您的方法。

然後只是返回您的項目,formattedDate

@RequestMapping(value = "/", method = RequestMethod.GET) 
    public String home(Locale locale, Model model) { 
     logger.info("Welcome home! the client locale is "+ locale.toString()); 

     Date date = new Date(); 
     DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); 

     String formattedDate = dateFormat.format(date); 

     model.addAttribute("serverTime", formattedDate); 

     return "main"; 
    } 

    @RequestMapping(value = "/serverTime", method = RequestMethod.GET) 
    @ResponseBody 
    public String serverTime(Locale locale, Model model) { 
     Date date = new Date(); 
     DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.LONG, DateFormat.LONG, locale); 

     return dateFormat.format(date); 
    } 
+0

啊,我這樣做了,但你會注意到我的問題的底線,這打破了我的觀點返回的方式。可以做到兩者嗎? – david99world 2012-04-17 16:41:39

+0

啊,對不起。你能夠使用AJAX嗎? 加載您的視圖,main,然後請求JSON數據。 – bvulaj 2012-04-17 16:44:24

+0

是的,我的AJAX請求基本上向控制器發出了它應該到達的頁面的請求,但是它也應該返回JSON的有效載荷。你是否建議我去一個網址的JSON響應和另一個爲HTML?這似乎有點討厭。 – david99world 2012-04-17 16:45:53

0

有轉換Java對象到JSON稱爲GSON庫:

http://code.google.com/p/google-gson/

順便說一句,如果你想發送一個Ajax響應,而不是刷新頁面,添加到@ResponseBody您的方法聲明:

public @ResponseBody String home(Locale locale, Model model) { .. } 

並返回您的JSON字符串(假設您沒有更新您的模型,如果是這種情況)。

+0

啊,如果你發現我的問題的底部,這看起來像它會打破,因爲它會返回視圖「主」我的觀點處理,是有可能做到這一點JSON響應,並保持操作中的我的看法控制器? – david99world 2012-04-17 16:42:50

+0

我認爲BrandonV已經回答了這個問題。 – JazzHands 2012-04-18 07:31:06