public class JsonView { public static ModelAndView Render(Object model, HttpServletResponse response) { MappingJacksonHttpMessageConverter jsonConverter = new MappingJacksonHttpMessageConverter(); MediaType jsonMimeType = MediaType.APPLICATION_JSON; try { jsonConverter.write(model, jsonMimeType, new ServletServerHttpResponse(response)); } catch (HttpMessageNotWritableException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } }
这是实现方法,下边是调用方法:
@RequestMapping(value="/users", method=RequestMethod.POST)public Object index(@RequestBody SearchUsersViewModel model, HttpServletResponse response) { model.setList(userService.getUsers(model)); if(true) { return new ModelAndView("controls/tables/users", "model", model); } else { return JsonView.Render(model, response); } }
这里全部是从Stack Overflow 粘贴的,原文地址:http://stackoverflow.com/questions/4917329/return-json-or-view-from-spring-mvc-controller
这个if条件句就是逻辑实现的,可以根据项目或者是流程的需要返回所需要的html或者是字符串!!
spring mvc 返回字符串或者是view的方法
时间: 2024-10-28 19:43:08