2012-04-17 84 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