响应HTML数据
方法一
//@ResquestMapping(path = " ", method = ResqusetMethod.Get)
@GetMapping("/path")
public ModelAndView fun(){
ModelAndView mav = new ModelAndView();
mav.addObject(name, value);
mav.setViewName("/Html path");
return mav;
}
方法二
//@ResquestMapping(path = " ", method = ResqusetMethod.Get)
@GetMapping("/path")
public String fun(Model model){
model.addAttribute(name, value);
return "/Html path";
}
响应JSON数据(异步请求)
如把 Java对象 --> JSON字符串 -->J S对象
//@ResponseBody 默认JSON序列化方式返回结果
@GetMapping("/path")
@ResponseBody
public Map<String, Object> fun(){
Map<String,Object> result = new HashMap<String, Object>();
result.put("code",0);
result.put("msg","");
result.put("data",value);
return result;
}
返回多个对象
@GetMapping("/path")
@ResponseBody
public Map<String, Object> fun(){
Lis<Map<String, Object>> list = new ArrayList<>();
Map<String, Object> oneResult = new HashMap<>();
oneResult.put(name1, value1);
list.add(mp);
oneResult.put(name2,value2);
list.add(mp);
Map<String, Object> result = new HashMap<String, Object>();
result.put("code",0);
result.put("msg","");
result.put("data",list);
return result;
}
这篇博客介绍了Spring MVC中两种响应数据的方法。方法一是使用ModelAndView返回HTML页面,将数据绑定到视图;方法二是直接返回字符串,结合Model将数据注入到视图。对于异步请求,通过@ResponseBody注解将Java对象转换为JSON并返回。示例展示了如何构造JSON响应,包括错误码、消息和数据内容。

被折叠的 条评论
为什么被折叠?



