道歉,如果這是重複的,但我找不到具體的例子。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)的名稱,所以我想保持它的工作方式相同。
啊,我這樣做了,但你會注意到我的問題的底線,這打破了我的觀點返回的方式。可以做到兩者嗎? – david99world 2012-04-17 16:41:39
啊,對不起。你能夠使用AJAX嗎? 加載您的視圖,main,然後請求JSON數據。 – bvulaj 2012-04-17 16:44:24
是的,我的AJAX請求基本上向控制器發出了它應該到達的頁面的請求,但是它也應該返回JSON的有效載荷。你是否建議我去一個網址的JSON響應和另一個爲HTML?這似乎有點討厭。 – david99world 2012-04-17 16:45:53