一個例子勝過千言萬語,直接上代碼
SpringMVC的Controller控制器返回值詳解
SpringMVC Controller 返回值幾種類型
Spring MVC 更靈活的控制 json 返回(自定義過濾字段) 另1
/** * * @return Bean */ @RequestMapping("/Test") @ResponseBody public TestBean test (){ log.debug("Test function"); TestBean testBean=new TestBean(); testBean.setName("haha"); return testBean; } /** * * @return Bean List */ @RequestMapping("/TestList") @ResponseBody public List<TestBean> testList (){ log.debug("TestList function"); List<TestBean> testBeanList=new ArrayList<TestBean>(); TestBean testBean1=new TestBean(); testBean1.setName("haha"); TestBean testBean2=new TestBean(); testBean2.setName("hehe"); testBeanList.add(testBean1); testBeanList.add(testBean2); return testBeanList; } /** * * @return JSON Data */ @RequestMapping("/TestJSONObject") public void testReturrnJSONWithoutBean(HttpServletRequest request,HttpServletResponse response) throws IOException{ log.debug("TestJSONObject function"); response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); PrintWriter writer=response.getWriter(); JsonObject jsonObject=new JsonObject(); jsonObject.addProperty("name","hehe jsonobject"); writer.println(jsonObject.toString()); writer.close(); } /** * * @return String */ @RequestMapping("/TestReturnPage") @ResponseBody public String testReturrnPage(){ log.debug("TestReturnPage"); return "/testpage"; } /** * The difference between model and modelandview is just sematic * */ /** * @return JSON ModelAndView */ @RequestMapping("/TestReturnModel") public String testReturnModel(Model model){ log.debug("testReturrnModel"); model.addAttribute("testmodel", "hello model"); return "testpage"; } /** * The difference between model and modelandview is just sematic * */ /** * @return JSON ModelAndView */ @RequestMapping("/TestReturnModelAndView") public ModelAndView testReturnModelAndView(){ log.debug("testReturrnModel"); ModelAndView mav = new ModelAndView("testpage"); mav.addObject("testmodel", "hello test model"); return mav; } /** * 獲取系統顯示的菜單 * * @param 無 * @return 返回JSON字符串,這是經過處理后的結構化樹形數據。 */ @RequestMapping(value = "/getShowedMenus", produces = "application/json; charset=utf-8") @ResponseBody public String getShowedMenus() { JsonArray menus=new JsonArray(); try{ menus=platformMenuService.getMenusForShow(); }catch(Exception e) { logger.error(e.toString()); e.printStackTrace(); } return menus.toString(); } /** * 從遠程數據中心中注銷登錄 * @param request * @param response * @return 返回邏輯值 */ @RequestMapping("/logout") @ResponseBody private boolean logout(HttpServletRequest request,HttpServletResponse response) { boolean retVal=false; try{ }catch(Exception e){ logger.error(e.toString()); } return retVal; } /** * 本地數據中心登錄至遠程數據中心。 * @param datacenterId * @return 返回是否登錄成功 */ @RequestMapping(value="/login",produces = "application/json; charset=utf-8") @ResponseBody public Boolean login(String dcId,HttpServletRequest request,HttpServletResponse response) { logger.info("datacenterId"+dcId); dcId="12"; Boolean retVal=false; try{ DatacatalogDatacenter dc=datacenterService.selectByPrimaryKey(dcId); String url="http://localhost:8080/"+request.getContextPath()+"/rest/datacatalog/datacenter/server/login?&no=121"; String val=HttpUtils.HttpPost(url); retVal=Boolean.parseBoolean(val); //retObject=new JSONObject(detail); }catch(Exception e){ logger.error(e.toString()); e.printStackTrace(); } return retVal; }
//使用request轉向頁面
@RequestMapping("/itemList2")
public void itmeList2(HttpServletRequest request, HttpServletResponse response) throws Exception {
// 查詢商品列表
List<Items> itemList = itemService.getItemList();
// 向頁面傳遞參數
request.setAttribute("itemList", itemList);
// 如果使用原始的方式做頁面跳轉,必須給的是jsp的完整路徑
request.getRequestDispatcher("/WEB-INF/jsp/itemList.jsp").forward(request, response);
}
也通過response實現頁面重定向:
response.sendRedirect("url")
如:
@RequestMapping("/itemList2") public void itmeList2(HttpServletRequest request, HttpServletResponse response) throws Exception { PrintWriter writer = response.getWriter(); response.setCharacterEncoding("utf-8"); response.setContentType("application/json;charset=utf-8"); writer.write("{\"id\":\"123\"}");
第一種,通過request.setAttribute進行返回。 @RequestMapping(value="/welcomeF") public String WelcomeF(User user,HttpServletRequest request){ System.out.println(user.toString()); /*通過setAttribute來設置返回*/ request.setAttribute("name", user.getName()); request.setAttribute("password", user.getPassword()); request.setAttribute("password", user.getHobby()); return "welcome"; } 第二種,通過ModelAndView進行返回。 @RequestMapping(value="/welcomeSeven") public ModelAndView WelcomeSeven(User2 user2){ /*通過ModelAndView來返回數據*/ ModelAndView mav = new ModelAndView("welcome"); mav.addObject("name", user2.getName()); mav.addObject("date", user2.getUdate()); return mav; } 第三種,通過model對象進行返回。 @RequestMapping(value="/welcomeEight") public String WelcomeEight(User2 user2,Model model){ /*通過Model對象來返回數據*/ model.addAttribute("name", user2.getName()); model.addAttribute("date", user2.getUdate()); return "welcome"; } 第四種,通過Map對象進行返回。 @RequestMapping(value="/welcomeNine") public String WelcomeNine(User2 user2,Map map){ /*通過Model對象來返回數據*/ map.put("name", user2.getName()); map.put("date", user2.getUdate()); return "welcome"; }
spring mvc返回json數據,只需要返回一個java bean對象就行,只要這個java bean 對象實現了序列化serializeable
@RequestMapping(value = { "/actor_details" }, method = { RequestMethod.POST }) @ResponseBody public ResultObject actorDetails(@RequestBody ActorDetailsRequest req) { logger.debug("查看{}主播信息", req.getAid()); if (req.getAid() == null || req.getAid().equals("null") || req.getAid().equals("")) { return new ResultObject(ResultCode.NULL_PARAM); } ActorAndUser result = actorServiceImpl.queryActorData(req.getAid()); return new ResultObject(result); }
ModelAndView
@RequestMapping(method=RequestMethod.GET) public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView("/user/index"); modelAndView.addObject("xxx", "xxx"); return modelAndView; }
@RequestMapping(method=RequestMethod.GET) public ModelAndView index(){ ModelAndView modelAndView = new ModelAndView(); modelAndView.addObject("xxx", "xxx"); modelAndView.setViewName("/user/index"); return modelAndView; }
Map
響應的view應該也是該請求的view。等同於void返回。
@RequestMapping(method=RequestMethod.GET) public Map<String, String> index(){ Map<String, String> map = new HashMap<String, String>(); map.put("1", "1"); //map.put相當於request.setAttribute方法 return map; }
@RequestMapping("/demo2/show") publicMap<String, String> getMap() { Map<String, String> map = newHashMap<String, String>(); map.put("key1", "value-1"); map.put("key2", "value-2"); returnmap; }
在jsp頁面中可直通過${key1}獲得到值, map.put()相當於request.setAttribute方法。
寫例子時發現,key值包括 - . 時會有問題.
String
對於String的返回類型,筆者是配合Model來使用的; @RequestMapping(method = RequestMethod.GET)2 public String index(Model model) { String retVal = "user/index"; List<User> users = userService.getUsers(); model.addAttribute("users", users); return retVal; }
或者通過配合@ResponseBody來將內容或者對象作為HTTP響應正文返回(適合做即時校驗); @RequestMapping(value = "/valid", method = RequestMethod.GET) public @ResponseBody String valid(@RequestParam(value = "userId", required = false) Integer userId,@RequestParam(value = "logName") String strLogName) { return String.valueOf(!userService.isLogNameExist(strLogName, userId)); }
具體參考:https://blog.csdn.net/u011001084/article/details/52846791 太長了,沒整理
@RequestMapping(value=”twoB.do”) public void twoBCode(HttpServletRequest request,HttpServletResponse response) { response.setContentType(“type=text/html;charset=UTF-8”); String s = “一堆字符串……”; response.getWriter().write(s); return; }
上面的太low,用下面的比較好
@RequestMapping(value=”getJosn.do”, produces=”text/html;charset=UTF-8”)
@ResponseBody
public String getTabJson(){
String json = “{“無主題”:”jjjjj”}”;
return json;
}