SpringMVC筆記:後端向前端返回數據的方式

1、通過request對象返回數據:

後臺:

@RequestMapping("/test1")
    public String test(HttpServletRequest request){
        String str1 = "HelloWorld!";
        request.setAttribute("str1",str1);
        return "";
    }

前臺獲取數據:

${requestScope.str1}

2、通過ModelAndView對象返回數據:

後臺:

@RequestMapping("/test2")
    public ModelAndView test2(){
        String str2 = "Hello!!";
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("str2",str2);
        modelAndView.setViewName("url");//這裏的url是服務器內地址,不能是任意地址;
        return modelAndView;
    }

前臺獲取數據:

${requestScope.str2}

3、通過ModelMap對象返回數據:

後臺: 

@RequestMapping(value="/test3")
	public String test3(ModelMap map) 
	{
		String str3 = "hello!!!";
		map.addAttribute("str3", str3);
		map.put("str3", str3);
        //以上兩種方式選一種即可
		return "";	
	}

前臺獲取數據:

${requestScope.str3}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章