Spring MVC 提供了多種方法來返回數據給前端。
@RequestMapping("/getData")
@ResponseBody
public Map<String, Object> getData() {
Map<String, Object> result = new HashMap<>();
result.put("name", "John");
result.put("age", 25);
return result;
}
@RequestMapping("/getData")
public ModelAndView getData() {
ModelAndView modelAndView = new ModelAndView("dataView");
modelAndView.addObject("name", "John");
modelAndView.addObject("age", 25);
return modelAndView;
}
@RequestMapping("/getData")
public String getData(Model model) {
model.addAttribute("name", "John");
model.addAttribute("age", 25);
return "dataView";
}
@RequestMapping("/getData")
public void getData(HttpServletResponse response) throws IOException {
PrintWriter writer = response.getWriter();
writer.write("Hello, World!");
writer.flush();
}
以上是幾種常見的返回數據給前端的方法,根據具體情況選擇合適的方法來返回數據。