道歉,如果这是重复的,但我找不到具体的例子。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