1、使用Model

我们可以使用Model来往域中存数据,然后使用之前的方式实现页面跳转、
例如:我们要求访问 /testRequestScope 这个路径时,能往Request域中存msg数据,并且跳转页面,在jsp中获取域中的数据。

  1. @RequestMapping("/testRequestScope")
  2. public String test04(Model model){
  3. model.addAttribute("msg","Hello");
  4. return "hello";
  5. }

2、使用ModelAndView

我们可以使用ModeAndView来往域中存数据和页面跳转。
例如:我们要求访问 /testRequestScope2 这个路径时,能往Request域中存msg数据,并且跳转页面,在jsp中获取域中的数据。

  1. @RequestMapping("/testRequestScope2")
  2. public ModelAndView test05(ModelAndView modelAndView){
  3. modelAndView.addObject("msg","Hello");
  4. modelAndView.setViewName("hello");
  5. return modelAndView;
  6. }

注意:要把ModelAndView对象作为方法的返回值!!

3、从Request域中获取数据

我们可以使用@RequestAttribute注解,把它加在方法参数上面,可以让SpringMVC帮我们从Request域中获取相关数据。

4、往Session域存数据并且跳转

我们可以使用@SessionAttributes 注解来进行标识,加在类上面。
用里面的属性来标识哪些数据要存入Session域中。
例如:我们要求访问 /testSessionScope这路径时,能往域中存msg数据,然后跳转到hello.jsp这个页面,在jsp中获取Session域中的数据,可以这样写:

  1. @Controller
  2. @SessionAttributes("msg")//标识name这个属性也要存储一份在Session
  3. public class RequestReponseSessionController {
  4. @RequestMapping("/testSessionScope")
  5. public String test06(Model model){
  6. model.addAttribute("msg","HelloSession");
  7. return "hello";
  8. }
  9. }

5、获取Session域中的数据

我们可以使用@SessionAttribute注解,把它加载方法参数上面,可以让SpringMVC帮我们从Session域中获取相关数据。

  1. @RequestMapping("/getSession")
  2. public String test07(@SessionAttribute("msg")String msg){
  3. System.out.println(msg);
  4. return "hello";
  5. }