1、使用Model
我们可以使用Model来往域中存数据,然后使用之前的方式实现页面跳转、
例如:我们要求访问 /testRequestScope 这个路径时,能往Request域中存msg数据,并且跳转页面,在jsp中获取域中的数据。
@RequestMapping("/testRequestScope")
public String test04(Model model){
model.addAttribute("msg","Hello");
return "hello";
}
2、使用ModelAndView
我们可以使用ModeAndView来往域中存数据和页面跳转。
例如:我们要求访问 /testRequestScope2 这个路径时,能往Request域中存msg数据,并且跳转页面,在jsp中获取域中的数据。
@RequestMapping("/testRequestScope2")
public ModelAndView test05(ModelAndView modelAndView){
modelAndView.addObject("msg","Hello");
modelAndView.setViewName("hello");
return modelAndView;
}
注意:要把ModelAndView对象作为方法的返回值!!
3、从Request域中获取数据
我们可以使用@RequestAttribute注解,把它加在方法参数上面,可以让SpringMVC帮我们从Request域中获取相关数据。
4、往Session域存数据并且跳转
我们可以使用@SessionAttributes 注解来进行标识,加在类上面。
用里面的属性来标识哪些数据要存入Session域中。
例如:我们要求访问 /testSessionScope这路径时,能往域中存msg数据,然后跳转到hello.jsp这个页面,在jsp中获取Session域中的数据,可以这样写:
@Controller
@SessionAttributes("msg")//标识name这个属性也要存储一份在Session
public class RequestReponseSessionController {
@RequestMapping("/testSessionScope")
public String test06(Model model){
model.addAttribute("msg","HelloSession");
return "hello";
}
}
5、获取Session域中的数据
我们可以使用@SessionAttribute注解,把它加载方法参数上面,可以让SpringMVC帮我们从Session域中获取相关数据。
@RequestMapping("/getSession")
public String test07(@SessionAttribute("msg")String msg){
System.out.println(msg);
return "hello";
}