srringmvc中Controller向前端传值

1、前言

在学习javaweb时,后端向前端传值,主要是通过request对象来传值。而在springmvc框架中,Controller层要向前端传值,主要通过ModelandView对象Model来实现,注解@SessionAttributes也可以用来传值。下面就介绍一下ModelandView对象ModelModelMap@SessionAttributes`和它们的使用方法。

2、ModelandView

ModelandView是一个包含视图名称或视图对象及一些数据模型的对象,在控制器处理完请求后将它返回到中央控制器。我们可以在ModelandView中放入参数,指定返回的页面。ModelAanView对象被放置在request对象中,jsp页面可以直接通过el表达式直接访问获取参数。若要使用ModelandView,则需要我们自己去new一个

3、Model

Model是一个接口,它的实现类为ExtendedModelMap,继承ModelMap类ModelMap类实现了Map接口。它可以用来传递模型数据,但不能做业务寻址。

4、ModelMap

ModelMap可以说结合Model和Map,既可以Model的方法传参,也可以使用Map的方法传参,但它仍然不能做业务寻址。

5、@SessionAttributes

该注解可以使Model中的属性同步到session中,它只能注解在类上,不能在方法上。

5、Controller向前端传值示例

1、使用ModelandView传值

@RequestMapping("/test1")
public ModelAndView test1() {
	ModelAndView mv = new ModelAndView();
    //将数据放入对象中
	mv.addObject("username", "test1");
	mv.addObject("password", "test1test");
    //放入jsp路径
	mv.setViewName("success");
    //返回ModelAndView对象
	return mv;
}

2、使用Model传值

@RequestMapping("/test2")
public String test2(Model model) {
	model.addAttribute("username", "test3");
	model.addAttribute("password", "test3test");
	return "success";
}

3、使用ModelMap传值

@RequestMapping("/test4")
public String test4(ModelMap model) { 
	model.addAttribute("username", "test4");
	model.put("password", "test4test");
	return "success";
}

4、使用Map传值

@RequestMapping("/test2")
public String test2() {
	Map<String,Object> map = new HashMap<>();
	map.put("username", "test2");
	map.put("password", "test2test");
	return "success";
}
posted @ 2019-06-01 16:43  hamawep  阅读(1040)  评论(0编辑  收藏  举报