controller进行数据保存以及如何进行重定向跳转

1. 数据保存到request作用域的方式.

  1. 使用ModelAndView,那么该方法的返回类型必须是ModelAndView
  2. 使用Model, 方法的返回值还是字符串类型。
  3. 使用Map.方法的返回值还是字符串类型。
  4. 原始的HttpServletRequest对象保存
     1 @Controller
     2 @RequestMapping("user")
     3 
     4 public class UserController {
     5     @RequestMapping("index.do")
     6     public ModelAndView Example() {
     7         ModelAndView mv=new ModelAndView("index");
     8         mv.addObject("name", "张三");        
     9         return mv;
    10     }
    11     
    12     @RequestMapping("index2.do")
    13     public String Example(Model model) {        
    14         model.addAttribute("name", "小明");    
    15         return "redirect:index.jsp";
    16     }
    17     
    18     @RequestMapping("index3.do")
    19     public String Example(Map<String, Object> map) {        
    20         map.put("name", "小美");
    21         return "index";
    22     }
    23     
    24     @RequestMapping("index5.do")
    25     public String Example(HttpServletRequest requset) {        
    26         requset.setAttribute("name", "mammanman");
    27         return "index";
    28     }
    29 }    

1.2 数据保存到session作用域的方式.

  1. 使用原始的HttpSession保存。
    1 @Controller
    2 @RequestMapping("user")
    3 public class UserController {
    4     @RequestMapping("index4.do")
    5     public String Example(HttpSession session) {        
    6         session.setAttribute("name", "xiaozhi");
    7         return "index";
    8     }
  2. 使用注解@SessionAttributes(name={key1,key2})
    @Controller
    @RequestMapping("user")
    @SessionAttributes(names= {"name"})//键名叫name的保存的作用域为session
    public class UserController {
        @RequestMapping("index2.do")
        public String Example(Model model) {        
            model.addAttribute("name", "小明");    
            return "index";
        }
    }

2. Controller如何进行重定向跳转。

1 @RequestMapping("index2.do")
2     public String Example(Model model) {        
3         model.addAttribute("name", "小明");    
4         return "redirect:index.jsp";
5     }

在return后写redirect+要跳转的页面

原文地址:https://www.cnblogs.com/mcl2238973568/p/11455463.html